1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <stdio.h>
void print_list(int *ar, int n) { int i; printf("[ "); for (i=0; i<n; i++) { printf("%d ", ar[i]); } printf("]\n");
}
int select_max(int *ar, int left, int right) { int max = left; int i = left; while (++i <= right) { if (ar[i] > ar[max]) { max = i; } } return max; }
void selection_sort(int *ar, int n) { int i, max, tmp; for (i=n-1; i>=1; i--) { max = select_max(ar, 0, i); if (max != i) { tmp = ar[i]; ar[i] = ar[max]; ar[max] = tmp; } }
}
int main(int argc, char *argv[]) { int a[] = {5, 3, 16, 2, 10, 14}; int len=sizeof(a)/sizeof(int); printf("begin: "); print_list(a, len); selection_sort(a, len); printf("end "); print_list(a, len); return 0; }
|