排序 - 歸併排序(C語言)
阿新 • • 發佈:2021-06-19
時間複雜度:O(NlogN)
空間複雜度:O(N)
穩定性:穩定
// 歸併排序 void merge_sort(int list[], int n) { /* perform a merge sort on the list. */ int length = 1; int extra[100]; while (length < n) { merge_pass(list, extra, n, length); length *= 2; merge_pass(extra, list, n, length); length*= 2; } } // 歸併排序: 歸併兩個已排序的表,例如:int sorted_list[10] = { 2,3,5,6,9,1,4,10,12,14 },則 merge(sorted_list, sorted, 0, 4, 9); void merge(int list[], int sorted[], int i, int m, int n) { /* merge two sorted lists: list[i], ..., list[m], and list[m+1], ..., list[n]. These lists are sorted to obtain a sorted list: sorted[i], ..., sorted[n]*/ int j, k, t; j = m + 1; k = i; while (i <= m && j <= n) { if (list[i] <= list[j]) sorted[k++] = list[i++]; else sorted[k++] = list[j++]; } if (i > m) /* sorted[k], ... , sorted[n] = list[j], ..., list[n] */ for(t = j; t <= n; t++) sorted[k + t - j] = list[t]; else /* sorted[k], ... , sorted[n] = list[i], ..., list[m] */ for (t = i; t <= m; t++) sorted[k + t - i] = list[t]; } // 單次歸併排序 void merge_pass(int list[], int sorted[], int n, int length) { /* perform one pass of the merge sort. It merges adjacent pairs of sub-lists from list into sorted. n is the number of elements in the list. length is the length of the sub-list. */ int i, j; for (i = 0; i <= n - 2 * length; i += 2 * length) merge(list, sorted, i, i + length - 1, i + 2 * length - 1); if (i + length < n) merge(list, sorted, i, i + length - 1, n - 1); else for (j = i; j < n; j++) sorted[j] = list[j]; }