归并排序

来源:互联网 发布:西安交通网络学院 编辑:程序博客网 时间:2024/06/11 05:31

归并排序就是利用归并的思想实现的排序方法。它的原理是假设初始序列含有n个记录,则可以看出是n个有序的字序列,每个子序列的长度为1,然后两两归并,。。。,如此重复,直至得到一个长度为n的有序序列为止。

int sortList[10] = {8,1,-1,3,1,4,6,12,-5,3};//合并两个数组的函数void merge1(int *a, int first, int middle, int last, int *temp){int i = first, j = middle + 1;int n = middle, m = last;int k = 0;while(i <= n && j <= m){if (a[i] < a[j]){temp[k++] = a[i++];}elsetemp[k++] = a[j++];}while(i <= n){temp[k++] = a[i++];}while(j <= m){temp[k++] = a[j++];}for (int i = 0; i < k; i++){a[first + i] = temp[i];}}//递归的调用合并函数void merge2(int *a, int first, int last, int *temp){if(first < last){int middle = (first + last) / 2;merge2(a, first, middle, temp);merge2(a, middle + 1, last, temp);merge1(a, first, middle, last, temp);}}int _tmain(int argc, _TCHAR* argv[]){int temp[10];cout<<"未排序之前:";print();merge2(sortList, 0, 9, temp);cout<<"排序之后:";print();cin.get();return 0;}