1.问题
二分归并排序:对n个不同的数构成的数组A[1…n]进行排序,其中n=2^k
2.解析
二分归并排序分为两步:二分+归并,体现了分治思想,即先使每个子序列有序,再使其合成的序列有序,因此为实现这个算法需要写两个函数,用于二分和归并。
3.设计
核心代码设计:
(1)
void mergeSort( int a[ ], int left, int right, int temp[ ] ){
if (left < right) {
mergeSort(left part);
mergeSort(right part);
merge(ordered left and right part);
}
}
(2)
void merge( int a[ ], int left, int mid, int right, int temp[ ] ){
int startA, startB,pos=0;
while (startA<=mid&&startB<=right) {
左右两段进行比较,较小的放入temp数组,startA/startB后移;
}
将a中没进行比较的数据直接放入temp数组;
更新a数组为归并后的序列;
}
4.分析
复杂度:
(1)最坏情况为n-1,时间复杂度为O(nlogn),例如:2,4,6;1,3,5 比较次数为5
(2)最好情况为n/2,时间复杂度为O(nlogn),例如:1,2,3;4,5,6 比较次数为3
(3)平均复杂度为O(nlogn)
5.源码
[github源码地址]
https://github.com/henryzhang6686/myAlgorithmCode