講一組有順序的元素按大小(只要定義能夠返回true或false的比較關係,非必定數值比較)從新調整順序。算法
歸併排序是分而治之策略,每次把兩個已經排序的數組按大小關係。算法實現採用了遞歸實現,依次將數組長度(1,2...n/4,n/2,n)內的元素排序合併。數組
void merge(long long int* arr, long long int* tmp, int left, int right, int rightEnd) { int i, leftEnd, num, tmpPos; leftEnd = right - 1; tmpPos = left; num = rightEnd - left + 1; while(left <= leftEnd && right <= rightEnd) { if (arr[left] <= arr[right]) { tmp[tmpPos++] = arr[left++]; } else { tmp[tmpPos++] = arr[right++]; } } while(left <= leftEnd) { tmp[tmpPos++] = arr[left++]; } while(right <= rightEnd) { tmp[tmpPos++] = arr[right++]; } for (i = 0; i < num; i++, rightEnd--) { arr[rightEnd] = tmp[rightEnd]; } } void mSort(long long int* arr, long long int* tmp, int left, int right, int len) { int center; int i; if (left < right) { center = (left + right) / 2; mSort(arr, tmp, left, center, len); mSort(arr, tmp, center + 1, right, len); merge(arr, tmp, left, center + 1, right); printf("合併參數:%d %d 結果:", left, right); for (i = 0; i < len; i++) { printf("%lld ", arr[i]); } printf("\n"); } } long long int* elrSortMerge(long long int* arr, int len) { long long int* tmp; tmp = malloc(len * sizeof(long long int)); if (tmp) { mSort(arr, tmp, 0, len - 1, len); free(tmp); } else { printf("no space for sort merge\n"); } return arr; }
#include <stdio.h> #include <stdlib.h> #include "elr_sort_merge.h" int main(int argc, char **argv){ int i; long long int arr[] = {6, 2, 4, 1, 3, 5, 0, 8, 9, -1, 7}; elrSortMerge(arr, 11); printf("%d\n", (int)(sizeof(arr) / sizeof(long long int))); for (i = 0; i < 11; i++) { printf("%lld ", arr[i]); } printf("\n"); return 0; }
合併參數:0 1 結果:2 6 4 1 3 5 0 8 9 -1 7 合併參數:0 2 結果:2 4 6 1 3 5 0 8 9 -1 7 合併參數:3 4 結果:2 4 6 1 3 5 0 8 9 -1 7 合併參數:3 5 結果:2 4 6 1 3 5 0 8 9 -1 7 合併參數:0 5 結果:1 2 3 4 5 6 0 8 9 -1 7 合併參數:6 7 結果:1 2 3 4 5 6 0 8 9 -1 7 合併參數:6 8 結果:1 2 3 4 5 6 0 8 9 -1 7 合併參數:9 10 結果:1 2 3 4 5 6 0 8 9 -1 7 合併參數:6 10 結果:1 2 3 4 5 6 -1 0 7 8 9 合併參數:0 10 結果:-1 0 1 2 3 4 5 6 7 8 9