程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SWAP(a, b, t) ((t) = (a), (a) = (b), (b) = (t))
#define CMP(a, b) (((a) < (b)) ? -1 : ((a) == (b)) ? 0 : 1)
#define N 10
void sort(int *a, int n) {
int i = 1, left = 0, right = n - 1, l, r, j, t;
while(left < right) {
l = left + 1;
r = right - 1;
for(j = left; j < right; j++) {
if(CMP(a[j], a[j + 1]) > 0) {
SWAP(a[j], a[j + 1], t);
r = j;
}
}
right = r;
for(j = right; j > left; j--) {
if(CMP(a[j], a[j - 1]) < 0) {
SWAP(a[j], a[j - 1], t);
l = j;
}
}
left = l;
printf("\n第%d次排序:\n", i++);
printf("left = %d\tright = %d\n", left, right);
for(j = 0; j < n; j++)
printf("%d ", a[j]);
puts("");
}
}
int main(void) {
int i, a[N];
srand((unsigned int)time(NULL));
for(i = 0; i < N; i++)
a[i] = 1 + (int)(10.0 * rand() / (RAND_MAX + 1.0));
puts("原始数据(N = 10):");
for(i = 0; i < N; i++)
printf("%d ", a[i]);
puts("");
sort(a, sizeof(a) / sizeof(a[0]));
return 0;
}