/*************** 并归排序 ***************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define LEN 5 void arr_init(int num[], int len) { int i; srand(time(NULL)); for(i = 0; i < len; i++){ num[i] = rand()%50; } } void arr_print(int num[], int len) { int i; for(i = 0; i < len; i++){ printf("%d ", num[i]); } printf("\n"); } void merge(int num[], int start, int end) { int mid, lenl, lenr, i, j, k; int *pl, *pr; mid = (start + end) / 2; lenl = mid - start + 1; lenr = end - mid; pl = (int *)malloc(lenl * sizeof(int)); pr = (int *)malloc(lenr * sizeof(int)); if(!pl || !pr){ printf("malloc fail\n"); exit(1); } memcpy(pl, num + start, lenl * sizeof(int)); memcpy(pr, num + mid + 1, lenr * sizeof(int)); i = j = 0, k = start; while(i < lenl && j < lenr){ if(pl[i] < pr[j]){ num[k++] = pl[i++]; }else{ num[k++] = pr[j++]; } } if(i < lenl){ memcpy(num + k, pl + i, (lenl - i) * sizeof(int)); } if(j < lenr){ memcpy(num + k, pr + i, (lenl - i) * sizeof(int)); } free(pl); free(pr); } void merge_sort(int num[], int start, int end) { if(start >= end) return; int mid = (start + end ) / 2; merge_sort(num, start, mid); merge_sort(num, mid + 1, end); merge(num, start, end); } int main(void) { int num[LEN]; arr_init(num, LEN); arr_print(num, LEN); merge_sort(num, 0, LEN - 1); arr_print(num, LEN); return 0; }