有多种排序方法,快排与归并时间复杂度O(nlogn),其它为O(n*n)
一、快速排序
#include
#include
#define N 100
int A[N];
void quick_sort(int left,int right)
{
int i,j,tmp;
if(left>=right)
{
return;
}
tmp=A[left];
i=left;
j=right;
while(i
while(i
{
j--;
}
A[i]=A[j];
while(i
i++;
}
A[j]=A[i];
}
A[i]=tmp;
quicksort(left,i-1);
quicksort(i+1,right);
}
int main()
{
......
quicksort(0,N-1);
......
}
二、冒泡排序
#include
#include
#define N 10
int A[N];
void bubble_sort(int A[])
{
int i,j,k;
for(i=0;i<=N-1;i++)
{
for(j=0;j
if(A[j]>A[j+1])
{
t=A[j];
A[j]=A[j+1];
A[j+1]=t;
}
}
}
}
int main()
{
......
bubble_sort(A);
......
}
三、插入排序
#include
#include
#define N 20
int A[N];
void insert_sort(int A[])
{
int i,j,tmp;
for(i=1;i
tmp=A[i];
j=i-1;
while(j>=0&&A[j]>tmp)
{
A[j+1]=A[j];
j--;
}
A[j+1]=tmp;
}
}
int main()
{
......
insert_sort(A);
......
}
四、选择排序
#include
#include
#define N 20
int A[N];
void select_sort(int A[])
{
int i,j,k,max,pos;
for(i=0;i
max=-1;
for(j=0;j
if(A[j]>max)
{
max=A[j];
pos=j;
}
}
A[pos]=A[N-i-1];
A[N-i-1]=max;
}
}
int main()
{
......
select_sort(A);
......
}
五、归并排序
#include
#include
#define N 20
int A[N],B[N];
viod merge_sort(int left,int right)
{
int i,j,k,m;
if(left>=right)
return;
else if(right==left+1)
{
A[left]+=A[right];
A[right]=A[left]-A[right];
A[left]=A[left]-A[right];
return;
}
m=(left+right)/2;
merge_sort(left,m);
merge_sort(m+1,right);
for(i=left;i<=right;i++)
{
B[i]=A[i];
}
i=left;
j=m+1;
k=left;
while(i<=m&&j<=right)
{
if(B[i]<=B[j])
{
A[k++]=B[i++];
}
else
{
A[k++]=B[j++];
}
}
while(i<=m)
{
A[k++]=B[i++];
}
while(j<=right)
{
A[k++]=B[j++];
}
}
int main()
{
......
merge_sort(A);
......
}