排序算法模板(C语言版)
1.快速排序
//By LYLtim void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void QSort(int l, int r) { int lp = l, rp = r, m = (l + r) >> 1; while (lp < rp) { while (a[lp] < a[m]) lp++; while (a[rp] > a[m]) rp--; if (lp <= rp) swap(&a[lp++], &a[rp--]); } if (l < rp) QSort(l, rp); if (lp < r) QSort(lp, r); }
C语音标准库函数qsort用法
1 int cmp(const void *a,const void *b) { 2 return ( *(int*)a - *(int*)b ); 3 } 4 qsort(a, n, sizeof(int), cmp);
详见:http://www.cplusplus.com/reference/cstdlib/qsort
2.归并排序
//By LYLtim void merge(int start, int mid, int end) { int pl, pr, p = start, len1 = mid - start + 1, len2 = end - mid, left[len1], right[len2]; for (pl = 0; pl < len1; pl++) left[pl] = a[start+pl]; for (pr = 0; pr < len2; pr++) right[pr] = a[mid+1+pr]; pl = pr = 0; while (pl < len1 && pr < len2) if (left[pl] < right[pr]) a[p++] = left[pl++]; else a[p++] = right[pr++]; while (pl < len1) a[p++] = left[pl++]; while (pr < len2) a[p++] = right[pr++]; } void sort(int start, int end) { if (start < end) { int mid = (start + end) >> 1; sort(start, mid); sort(mid+1, end); merge(start, mid, end); } }
3.希尔排序
//By LYLtim void ShellSort(int a[], unsigned n) { unsigned gap, i, j; for (gap = n >> 1; gap > 0; gap >>= 1) for (i = gap; i < n; i++) for (j = i - gap; j >= 0 && a[j] > a[j + gap]; j -= gap) swap(&a[j], &a[j + gap]); }