#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#define swap(a, b) ({
__typeof(a) __temp = a;
a = b; b = __temp;
})
#define TEST(arr, n, func, args...) {
int *num = (int *)malloc(sizeof(int) * n);
memcpy(num, arr, sizeof(int) * n);
printf("
");
output(num, n);
printf(#func);
func(args);
output(num, n);
free(num);
}
void insert_sort(int *num, int n) {
for (int i = 1; i < n; ++i)
for (int j = i; j > 0 && num[j] > num[j - 1]; --j) {
swap(num[j], num[j - 1]);
}
return ;
}
void bubble_sort(int *num, int n) {
int k = 0;
for (int i = 0; i < n - 1 && !k; ++i) {
k = 0;
for (int j = 0; j < n - i; ++j ) {
num[j] < num[j + 1] && swap(num[j], num[j + 1]);
num[j] < num[j + 1] && (k = 1);
}
}
return ;
}
void merge_sort(int *num, int l, int r) {
if (r - l <= 1) {
r - l == 1 && num[l] > num[r] && swap(num[l], num[r]);
return ;
}
int mid = (l + r) >> 1;
merge_sort(num, l, mid);
merge_sort(num, mid + 1, r);
int *temp = (int *)malloc(sizeof(int) * (r - l + 1)), lt = l, rt = mid + 1, k = 0;
while (lt <= mid || rt <= r) {
if (rt > r && lt <= mid || lt <= mid && num[lt] <= num[rt]) temp[k++] = num[lt++];
if (lt > mid && rt <= r || rt <= r && num[lt] >= num[rt]) temp[k++] = num[rt++];
}
memcpy(num + l, temp, sizeof(int) * (r - l + 1));
free(temp);
return ;
}
void output(int *num, int n) {
printf("
");
for (int i = 0; i < n; i++) printf("%d", num[i]), printf(", ");
}
void input(int *num, int n) {
for (int i = 0; i < n; ++i) num[i] = rand() % 100;
}
int main() {
srand(time(0));
#define MAX 20
int arr[MAX], oj = rand() % 3;
input(arr, MAX); output(arr, MAX);
for (int i = 0; i < MAX; ++i, oj = rand() % 3)
switch (oj) {
case 0: TEST(arr, MAX, insert_sort, num, MAX);
break;
case 1: TEST(arr, MAX, bubble_sort, num, MAX);
break;
case 2: TEST(arr, MAX, merge_sort, num, 0, MAX - 1);
}
#undef MAX
return 0;
}