C語言:歸並排序
阿新 • • 發佈:2017-12-23
tar merge ret void class while std stdio.h 歸並排序
歸並排序(C語言)。
先上代碼,理論會後面一起總結。
1. 遞歸
2. 非遞歸
#include <stdio.h> #include <stdlib.h> #include <string.h> void merge_sort(int* arr, int length) { int step = 1; //區間步長 int l[length], r[length]; //gcc, 兩個臨時數組,分別表示待歸並的兩個區間 //int l[100], r[100]; //vc while(step < length) {int startloc = 0; //歸並區間的開始下標 while(startloc < length - step) { //歸 int len_l, len_r; //左右待歸並區間的長度 len_l = len_r = step; memcpy(l, arr + startloc, sizeof(int) * len_l); if(startloc + 2 * step > length) { len_r= length - startloc - step; } memcpy(r, arr + startloc + step, sizeof(int) * len_r); //並 int i = 0, j = 0, k = startloc; while(i < len_l && j < len_r) { arr[k++] = l[i] < r[j] ? l[i++] : r[j++]; }while(i < len_l) { arr[k++] = l[i++]; } startloc += 2 * step; } step *= 2; } } int main() { int arr[11] = {-1, 2, 4, -12, 4, 0, 0, 12, 23, -4, 7000}; merge_sort(arr, 11); for(int i = 0; i < 11; ++i) { printf("%d ", arr[i]); } printf("\n"); return 0; }
C語言:歸並排序