View Code
#include <stdio.h> #include <stdlib.h> #include <string.h> void merge(int *a, int p, int q, int r) { int s1, e1; int s2, e2; int *temp = malloc((r-p+1) * sizeof(int)); memset(temp, 0, sizeof(int)); s1 = p; e1 = q; s2 = q+1; e2 = r; int index = s1; int i = 0; while(s1 <= e1 && s2 <= e2) { if (a[s1] < a[s2]) { temp[i++] = a[s1]; s1++; } else { temp[i++] = a[s2]; s2++; } } while (s1 < e1+1) { temp[i++] = a[s1]; s1++; } while (s2 < e2+1) { temp[i++] = a[s2]; s2++; } for (i = 0; i < r-p+1; i++) { a[index + i] = temp[i]; } free(temp); } void naturalMergeSort(int *a, int n) { int *index = malloc(n*sizeof(int)); memset(index, 0, sizeof(int)); int k = 1; int i; for (i = 0; i < n - 1; i++) { if (a[i] > a[i+1]) { index[k++] = i; } } index[k] = n - 1; int s = 1; for (i = k; i > 1; i = (i % 2 == 0 ? (i / 2) : (i / 2 + 1))) { int count = i / 2; int p = 0; int q = s; int r = 2*s; if (r > k ) { r = k - 1; } merge(a, index[p], index[q], index[r]); int j; for (j = 1; j < count; j++) { p = r; q = p + s; r = q + s; if (r > k) { r = k -1; } merge(a, index[p] + 1, index[q], index[r]); } s += s; } } int main() { int a[8] = {4, 8, 3, 7, 1, 5, 6, 2}; naturalMergeSort(a, 8); int i; for (i = 0; i < 8; i++) { printf("%d ", a[i]); } printf("\n"); return 0; }