1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <stdio.h> #include <stdlib.h>
void merge(int arr[], int start, int mid, int end) { int* temp = (int*)malloc((end - start + 1) * sizeof(int)); if (temp == NULL) { printf("Failed to allocate memory for temp array!"); return; } int k = 0; int i = start; int j = mid + 1; while (i <= mid && j <= end) { if (arr[i] < arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } } while (i <= mid) { temp[k++] = arr[i++]; } while (j <= end) { temp[k++] = arr[j++]; } k = 0; while (start <= end) { arr[start++] = temp[k++]; } free(temp); }
void merge_sort(int arr[], int start, int end) { if (start < end) { int mid = (start + end) / 2; merge_sort(arr, start, mid); merge_sort(arr, mid + 1, end); merge(arr, start, mid, end); } }
int main() { int arr[] = { 10,9,8,7,6,5,4,3,2,1 }; int sz = sizeof(arr) / sizeof(arr[0]); int start = 0; int end = sz - 1; merge_sort(arr, start, end); for (int i = 0; i < sz; i++) { printf("%d ", arr[i]); }
return 0; }
输出: 1 2 3 4 5 6 7 8 9 10
|