#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#define swape(a, b) ({
__typeof (a) temp;
temp = a;
a = b;
b = temp;
})
#define TES(arr, max, func, args...) {
int *num = (int *)malloc(sizeof(int) * max);
memcpy(num, arr, sizeof(int) * max);
func(args);
printf(#func" ");
output(num, max);
printf("
");
free(num);
}
void select_sort(int *num, int m) {
for (int i = 0, ind, j; i < m - 1; i++) {
ind = i;
for (j = i + 1; j < m; j++) num[ind] > num[j] && (ind = j);
swape(num[ind], num[i]);
}
return ;
}
/*
* 普通快速排序
void quick_sort(int *num, int ml, int m) {
int l = ml, r = m, sk = num[l];
while(l < r) {
while(num[r] >= sk) r--;
l <= r && (num[l++] = num[r]);
while(l < r && num[l] < sk) l++;
l <= r && (num[r--] = num[l]);
}
num[l] = sk;
l > ml && (quick_sort(num, ml, l - 1), 1);
l < m && (quick_sort(num, l + 1, m), 1);
return ;
}
*/
/*
* 优化后的快速排序
* 单边递归
* 基准值优化
* 取消监督
*/
void quick_sort(int *num, int ml, int m) {
while (ml < m) {
int l = ml, r = m, sk = num[(l + r) >> 1];
do {
while (num[l] < sk) l++;
while (num[r] > sk) r--;
if (l <= r) {swape(num[l], num[r]); l++, r--;}
} while (l <= r);
quick_sort(num, ml, r);
ml = l;
}
return ;
}
void output(int *num, int m) {
for (int i = 0; i < m; i++, m - i && printf(" ")) printf("%d", num[i]);
printf("
");
return ;
}
void input(int *num, int m) {
for (int i = 0; i < m; i++) num[i] = rand() % 100;
return ;
}
int main() {
srand(time(0));
#define MAX 10
int arr[MAX], op = rand() % 2;
input(arr, MAX), output(arr, MAX);
for (int i = 0; i < MAX; i++, op = rand() % 2)
switch(op) {
case 0: TES(arr, MAX, select_sort, num, MAX);
break;
case 1: TES(arr, MAX, quick_sort, num, 0, MAX - 1);
break;
}
#undef MAX
return 0;
}