typedef int Item;
#define cmp(a,b) ((a) < (b))
#define swap(a,b) ({Item t; t=a; a=b; b=t;})
#define cmp_swap(a,b) if (cmp(a,b)) swap(a,b)
void select_sort(Item *a, int l, int r);
void insert_sort(Item *a, int l, int r);
void bubble_sort(Item *a, int l, int r);
|
/* min
* N: 0...N-1
* l...r
* */
void select_sort(Item *a, int l, int r)
{
int i,j;
int min;
for (i=l; i<r; i++) {
min = i;
for (j=i+1; j<=r; j++)
if (cmp(a[j], a[min]))
min = j;
swap(a[i], a[min]);
}
}
|
void insert_sort(Item *a, int l, int r)
{
int i,j;
Item v;
/* set a lookout */
for (i=r; i>l; i--) cmp_swap(a[i], a[i-1]);
for (i=l+2; i<=r; i++) {
v = a[i];
for (j=i; cmp(v, a[j-1]); j--)
a[j] = a[j-1];
a[j] = v;
}
}
|
void bubble_sort(Item *a, int l, int r)
{
int i,j;
for (i=l; i<r; i++) {
for (j=r; j>i; j--)
cmp_swap(a[j], a[j-1]);
}
}
|
test:
static void print_list_int(Item *a, int l, int r)
{
while (l<=r) {
printf("%d ", a[l]);
l++;
}
printf("\n");
}
int main()
{
Item a[] = {3,1,3,0,5,7,6,4};
int l=0,r=7;
print_list_int(a,l,r);
//select_sort(a,l,r);
//insert_sort(a,l,r);
bubble_sort(a,l,r);
print_list_int(a,l,r);
return 0;
}
阅读(884) | 评论(0) | 转发(0) |