排序算法-歸併排序

#include
using namespace std;
/*
歸併排序(MERGE-SORT)是建立在歸併操作上的一種有效的排序算法,該算法是採用分治法(Divide and Conquer)的一個非常典型的應用。
將已有序的子序列合併,得到完全有序的序列;即先使每個子序列有序,再使子序列段間有序。若將兩個有序表合併成一個有序表,稱爲二路歸併。
*/
int* MergeSort(int list[],int index1,int index2)
{
    if(index1==index2)//當只有一個元素時返回該元素
    {
        int *p=new int(list[index1]);
        return p;
    }
    int index=(index1+index2)/2;
    int*sorted1=MergeSort(list,index1,index);//將數組分成兩部分,左邊排序
    int*sorted2=MergeSort(list,index+1,index2);//右邊排序
    int* sorted=new int[index2-index1+1];//保存排序後的兩邊的元素合起來
    int c1,c2;c1=c2=0;
    for(int i=0;i<index2-index1+1;i++)
    {
        if(c2<=index2-index-1&&c1<=index-index1)//如果兩邊都有元素
        {
            if(sorted1[c1]<=sorted2[c2]&&c1<=index-index1)
            {
                sorted[i]=sorted1[c1];
                c1++;
            }
            else if(sorted1[c1]>sorted2[c2]&&c2<=index2-index)
            {
                sorted[i]=sorted2[c2];
                c2++;
            }
        }
        else if(c2>index2-index-1&&c1<=index-index1)//如果只有左邊有元素
        {
            sorted[i]=sorted1[c1];
                c1++;
        }
        else //如果只有右邊有元素
        {
            sorted[i]=sorted2[c2];
                c2++;
        }
    }
    delete sorted1,sorted2;
    return sorted;
}
int main()
{
    int list[]={3,4,5,2,1,7,7,6,5,9};
    int *sorted=MergeSort(list,0,9);
    for(int i=0;i<10;i++)
        cout<<sorted[i]<<" ";
    cout<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章