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
| #include <stdio.h>
#define SIZE(a) (sizeof(a)/sizeof(a[0])) #define N 7
void print_array(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); }
void merge_sort(int arrp[], int n); int main(void) {
int arr[N] = { 38,27,43,3,9,82,10 }; print_array(arr, N); merge_sort(arr,N);
return 0; } int tmp[N]; void merge(int arr[], int left, int mid, int right) { int i = left, j = mid + 1, k = left; while (i <= mid && j <= right) { if (arr[i] <= arr[j]) { tmp[k++] = arr[i++]; } else { tmp[k++] = arr[j++]; } } while (i <= mid) { tmp[k++] = arr[i++]; } while (j <= right) { tmp[k++] = arr[j++]; } for (int k = left; k <= right; k++) { arr[k] = tmp[k]; } } void m_sort(int arr[], int left, int right) { if (left >= right) { return; } int mid = left + (right - left >> 1); m_sort(arr, left, mid); m_sort(arr, mid + 1, right); merge(arr, left,mid, right);
print_array(arr, N); }
void merge_sort(int arr[], int n) { m_sort(arr, 0, n - 1); }
|