voidshell_sort(int arr[], int len) { int gap, i, j; int temp; for (gap = len >> 1; gap > 0; gap >>= 1)//向右移移位==整除2 for (i = gap; i < len; i++) { temp = arr[i]; for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap)//插入排序 arr[j + gap] = arr[j]; arr[j + gap] = temp; } }
intmin(int x, int y) { return x < y ? x : y; } voidmerge_sort(int arr[], int len) { int* a = arr; int* b = (int*) malloc(len * sizeof(int)); int seg, start; for (seg = 1; seg < len; seg += seg) {//外层循环用于控制归并的步长,每次循环 seg 的值会翻倍,直到大于等于数组长度 len。 for (start = 0; start < len; start += seg + seg) {//内层循环用于在当前步长下对数组进行归并操作,每次循环按照步长 seg 来划分子数组进行合并。 int low = start, mid = min(start + seg, len), high = min(start + seg + seg, len); int k = low; int start1 = low, end1 = mid; int start2 = mid, end2 = high; while (start1 < end1 && start2 < end2) b[k++] = a[start1] < a[start2] ? a[start1++] : a[start2++]; while (start1 < end1) b[k++] = a[start1++]; while (start2 < end2) b[k++] = a[start2++]; } int* temp = a; a = b; b = temp; } if (a != arr) { int i; for (i = 0; i < len; i++) b[i] = a[i]; b = a; } free(b); }