归并排序之C++实现

   将待排序序列R[0...n-1]看成是n个长度为1的有序序列,将相邻的有序表成对归并,得到n/2个长度为2的有序表;将这些有序序列再次归并,得到n/4个长度为4的有序序列;如此反复进行下去,最后得到一个长度为n的有序序列。归并排序的时间复杂度为O(nlogn)

   代码实现如下:

#include
#include

using namespace std;

void Merge(vector &arrays,int start,int end)
{
    vector TempArray(end-start+1,0);
    int mid=start+(end-start)/2;
    int temp=0;
    int templeft=start;
    int tempright=mid+1;
    for(;templeft<=mid&&tempright<=end;)
    {
        if(arrays[templeft]>arrays[tempright])
        {
            TempArray[temp++]=arrays[tempright++];
        }
        else
        {
            TempArray[temp++]=arrays[templeft++];
        }
    }
    if(templeft<=mid)
    {
        for(;templeft<=mid;)
            TempArray[temp++]=arrays[templeft++];
    }
    if(tempright<=end)
    {
        for(;tempright<=end;)
            TempArray[temp++]=arrays[tempright++];
    }
    for(auto i=start,j=0;i<=end;i++)
    {
        arrays[i]=TempArray[j++];
    }
}
void MergingSort(vector &arrays,int start,int end)
{
    if(end<=start)
        return;
    int mid=start+(end-start)/2;
    MergingSort(arrays,start,mid);
    MergingSort(arrays,mid+1,end);
    Merge(arrays,start,end);
}
int main(void)
{
    vector arrays={7,4,5,2,6,1,8,3,0,9};
    MergingSort(arrays,0,arrays.size()-1);
    for(auto c:arrays)
        cout<

猜你喜欢

转载自blog.csdn.net/u012021393/article/details/72629707