#include <stdio.h>
#define N 10
#define Item int
#define less(A,B) (A<B)
#define eq(A,B) (!less(A,B) && !less(B,A))
//#define swap(A,B) {Item t;t = A; A = B;B = t;}
#define swap(A,B) {A = A^B; B = A^B; A = A^B;}
#define compswap(A,B) if(less(A,B))swap(A,B);
/*********************** bubble sort method ***************************/
Item* bubble(Item* a,int n)
{
int i,j;
for(i = 0;i<N;i++)
for(j = i;j<N;j++)
compswap(a[j],a[i]);
return a;
}
/*********************** insert sort method **************************/
Item* insert(Item* a,int n)
{
int i,j;
Item key,temp;
for(i = 1;i<N;i++)
{
key = *(a+i);
j = i-1;
while(j>=0)
{
if(*(a+j)>key)
swap(*(a+j),*(a+j+1));
j--;
}
}
return a;
}
/*********************** select sort method **************************/
Item* select(Item* a,int n)
{
int i,j,k;
for(i = 0;i<N;i++)
{
k = i;
for(j = i+1;j<N;j++)
if(a[j]<a[k])
k = j;
if(i != k)
swap(a[k],a[i]);
}
return a;
}
int main(int argc,char *argv[])
{
int i;
Item a[N] = {'a','c','e','f','h','k','i','j','d','b'};
printf("Before:\n");
for(i = 0; i<N; i++)
printf("%d, ",a[i]);
printf("\n");
//Item* b = bubble(a,N);
Item* b = insert(a,N);
//Item* b = select(a,N);
printf("After:\n");
for(i = 0; i<N; i++)
printf("%d, ",b[i]);
printf("\n");
return 0;
}
排序:冒泡、插入、选择三体合一
最新推荐文章于 2022-01-17 08:52:56 发布