分类:
2007-09-27 16:41:26
#include "mergeSort.h" #include int buff[4092]; void mergeSort(int *A, int l, int r) { if(l == r) return; int m = (l + r) / 2; printf("mergeSort(A, %d, %d)\n", l, r); mergeSort(A, l, m); mergeSort(A, m + 1, r); merge(A, l, m, r); } void merge(int *A, int l, int m, int r) { int i = l; int j = m + 1; int k = 0; while((i <= m) && (j <= r)) { if(A[i] < A[j]) { buff[k++] = A[i++]; } else { buff[k++] = A[j++]; } } while(i <= m) { buff[k++] = A[i++]; } while(j <= r) { buff[k++] = A[j++]; } for(k = 0, i = l;i <= r;i++) { A[i] = buff[k++]; } } |
#ifndef MERGESORT_H #define MERGESORT_H void mergeSort(int *A, int l, int r); void merge(int *A, int l, int m, int r); #endif |
#include "mergeSort.h" #include #include #include #include void print_array(int *a, int len) { int i = 0; for(i = 0;i < len;i++) { printf("%d ", a[i]); } printf("\n"); } int main() { int i, len; int *A; printf("len = "); scanf("%d", &len); if( (A = (int *)malloc(sizeof(int) * len)) == NULL) { perror(strerror(errno)); return 1; } for(i = 0;i < len;i++) { A[i] = rand() % 100; } printf("Before merge sorting : "); print_array(A, len); mergeSort(A, 0, len - 1); printf("After merge sorting : "); print_array(A, len); return 0; } |