#include<stdio.h>//希尔排序 voidshell_sort(int arr[], int len) { int gap, i, j; int temp; for (gap = len >> 1; gap > 0; gap = gap >> 1)//gap = len/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; } }
intmain() {//主函数 int arr[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 }; int len = (int) sizeof(arr) / sizeof(*arr); printf("%d\n",sizeof(int)); shell_sort(arr, len); int i; for (i = 0; i < len; i++) printf("%d ", arr[i]); return0; }
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) { for (start = 0; start < len; start += 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); }
voidswap(int *x, int *y) { int t = *x; *x = *y; *y = t; } voidquick_sort_recursive(int arr[], int start, int end) { if (start >= end) return; int mid = arr[end]; int left = start, right = end - 1; while (left < right) { while (arr[left] < mid && left < right) left++; while (arr[right] >= mid && left < right) right--; swap(&arr[left], &arr[right]); } if (arr[left] >= arr[end]) swap(&arr[left], &arr[end]); else left++; if (left) quick_sort_recursive(arr, start, left - 1); quick_sort_recursive(arr, left + 1, end); } voidquick_sort(int arr[], int len) { quick_sort_recursive(arr, 0, len - 1); }