1 //递归实现归并排序 2 //l左边的起始位置,r右边起始位置,rightEnd右边终点位置 3 //merge函数用来合并两段有序序列 4 void merge(ElementType a[], ElementType t[], int l, int r, int rightEnd) { 5 int leftEnd, numElements, temp; 6 int i; 7 8 leftEnd = r - 1;//左边终止位置 9 temp = l;//有序序列的起始位置 10 numElements = rightEnd - l + 1;//全部元素个数 11 12 while (l <= leftEnd && r <= rightEnd) { 13 if (a[l] <= a[r]) 14 t[temp++] = a[l++]; 15 else 16 t[temp++] = a[r++]; 17 } 18 19 while (l <= leftEnd) t[temp++] = a[l++]; 20 while (r <= rightEnd) t[temp++] = a[r++]; 21 for (i = 0; i < numElements; i++, rightEnd--) a[rightEnd] = t[rightEnd]; 22 //将有序的t数组复制回a数组 23 } 24 //核心递归程序 25 void mSort(ElementType a[], ElementType t[], int l, int rightEnd) { 26 int center; 27 28 if (l < rightEnd) { 29 center = (l + rightEnd) / 2; 30 mSort(a, t, l, center);//递归解决左边 31 mSort(a, t, center + 1, rightEnd);//递归解决右边 32 merge(a, t, l, center + 1, rightEnd);//合并两段有序序列 33 } 34 } 35 //归并排序 36 void mergeSort(ElementType a[], int n) { 37 ElementType* t; 38 t = (ElementType*)malloc(n * sizeof(ElementType)); 39 40 if (t != NULL) { 41 mSort(a, t, 0, n - 1); 42 free(t); 43 } 44 else printf("空间不足"); 45 46 }