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
| #include <stdio.h> #include <stdlib.h> #include <limits.h>
int len; void print_list(int *list, int n) {
int i; printf("[ "); for (i=0; i<n; i++) { printf("%d ", list[i]); } printf("]\n"); }
void merge(int *a, int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; int *L = (int *)malloc((n1+1) * sizeof(int)); int *R = (int *)malloc((n2+1) * sizeof(int)); int i, j, k; for (i=0; i<n1; i++) { L[i] = a[p+i]; } for (j=0; j<n2; j++) { R[j] = a[q+j+1]; } L[i] = INT_MAX; R[j] = INT_MAX;
i = j = 0; for (k=p; k<=r; k++) { if (L[i] <= R[j]) { a[k] = L[i]; i++; } else { a[k] = R[j]; j++; } } free(L); free(R); print_list(a, len); }
void merge_sort(int *a, int p, int r) { if (p < r) { int q = (p + r) / 2; merge_sort(a, p, q); merge_sort(a, q+1, r); merge(a, p, q, r); } }
int main(int argc, char *argv[]) { int a[] = {3, 41, 52, 26, 38, 57, 9, 49}; len = sizeof(a) / sizeof(int); merge_sort(a, 0, len-1); return 0; }
|