排序算法之归并排序(写给自己看的。。。)
#include <stdio.h> #include <stdlib.h> void mergesort(int a[], int first, int last) ; int main(int argc, char *argv[]) { int ab[10]={9,8,7,6,5,4,3,2,1,10} ; int i; mergesort(ab, 0, 9); for(i=0;i<10;i++){ printf("%d->",ab[i]); } return 0; } // 利用分治大法,当分成的数组只有一个数字时就已经是有序数组了,只需要不断合并即可 //将有二个有序数列a[first...mid]和a[mid...last]合并 void mergearray(int a[], int first, int mid, int last) //默认两个数组有序 { int i = first, j = mid + 1; int m = mid, n = last; int k = 0;
int temp[last];//一个临时的数组 while (i <= m && j <= n) { if (a[i] <= a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= m) temp[k++] = a[i++]; while (j <= n) temp[k++] = a[j++]; //将得到的临时的已经合并的数组的数据复制到数组a for (i = 0; i < k; i++) a[first + i] = temp[i]; } void mergesort(int a[], int first, int last) { if (first < last) { int mid = (first + last) / 2; mergesort(a, first, mid); //左边有序 mergesort(a, mid + 1, last); //右边有序 mergearray(a, first, mid, last); //再将二个有序数列合并 } }
主要强调以下几点:
1.采用分治的方法,使得归并排序成为一种稳定的算法,O(nlogn);
2.两个有序数组合并的问题。(一般是合并两个数组到其中一个数组,其中建立一个临时数组起过渡,减少不必要的内存)
3.递归的使用。

浙公网安备 33010602011771号