两路合并排序,时间复杂度为nlogn
#include<iostream>
using namespace std;
//merge two subArray,one is A[i1]~A[j1],another is A[i2]~A[j2]
void MergeTwoArray(int A[],int i1,int j1,int i2,int j2)
{
int *tmp = new int[j2 - i1 + 1];
int i = i1, j = i2, k = 0;
while (i <= j1 && j <= j2)
{
//add samller one into tmp arrary
if (A[i] <= A[j])
{
tmp[k++] = A[i++];
}
else
{
tmp[k++] = A[j++];
}
}
while (i<=j1)
tmp[k++] = A[i++];
while (j<=j2)
tmp[k++] = A[j++];
for (i = 0; i < k; i++)
{
A[i1++] = tmp[i];
}
delete[]tmp;
}
void MergeSort(int A[],int n)
{
int i1, j1, i2, j2 = 0;
int size = 1;
while (size < n)
{
i1 = 0;
while (i1 + size < n)//存在两个序列,那就需要合并
{
//确定两个序列的边界
j1 = i1 + size - 1;
i2 = i1 + size;
if (i2 + size - 1 > n - 1)
{
j2 = n - 1;
}
else
j2 = i2 + size - 1;
MergeTwoArray(A,i1,j1,i2,j2);
//更新i1
i1 = j2 + 1;
}
size *= 2;
}
}
int main()
{
int A[10] = {5, 6, 8, 7, 9, 0, 1, 2, 3, 4 };
MergeSort(A, 10);
return 0;
}