归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
算法描述
- 把长度为n的输入序列分成两个长度为n/2的子序列;
- 对这两个子序列分别采用归并排序;
- 将两个排序好的子序列合并成一个最终的排序序列。
算法时间复杂度
平均时间复杂度、最好时间复杂度、最坏时间复杂度为O(nlogn)
代码实现
#include <iostream>
using namespace std;
void print(int arr[], int len)
{
for(int i = 0; i != len; i++)
cout << arr[i] << " ";
cout << endl;
}
void merge(int sourceArr[], int tempArr[], int startIndex, int midIndex, int endIndex)
{
int k = 0; // 临时数组索引
int i = startIndex;
int j = midIndex + 1;
while(i != midIndex + 1 && j != endIndex + 1)
{
if(sourceArr[i] > sourceArr[j])
tempArr[k++] = sourceArr[j++];
else
tempArr[k++] = sourceArr[i++];
}
while(i != midIndex + 1)
tempArr[k++] = sourceArr[i++];
while(j != endIndex + 1)
tempArr[k++] = sourceArr[j++];
for(i = startIndex, k = 0; i <= endIndex; i++)
sourceArr[i] = tempArr[k++];
}
void mergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex)
{
int midIndex = (startIndex + endIndex) / 2;
if(startIndex < endIndex){
mergeSort(sourceArr, tempArr, startIndex, midIndex); //左部分
mergeSort(sourceArr, tempArr, midIndex + 1, endIndex); //右部分
merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
}
}
int main()
{
int arr[10] = {9,8,7,6,5,4,3,2,1,0};
int temp[10] = { 0 };
mergeSort(arr, temp, 0, 9);
print(arr, 10);
return 0;
}
运行结果
0 1 2 3 4 5 6 7 8 9