直接插入排序、折半插入排序、2-路插入排序實現

來源:互聯網
上載者:User

        按照書上的說法,排序是電腦程式設計中的一種重要操作,它的功能是將一個資料元素(或記錄)的任意序列,重新排列成一個按關鍵字有序的序列。

        為了方便我們直接對整型數組進行排序。將數組元素按照小到大的順序排列。以後遇到什麼記錄、結構體排序演算法也一樣。這裡只給出實現,演算法說明請看嚴蔚敏的書。


//直接插入排序

void InsertSort(int array[],size_t size)//數組的array空出來,做哨兵。size為數組的長度{    for(int i=2;i<size;++i)    {        if(array[i]<array[i-1])        {            array[0]=array[i];            array[i]=array[i-1];            int j;            for(j=i-2;array[0]<array[j];--j)            {                array[j+1]=array[j];            }//for            array[j+1]=array[0];             }//if        }//for    }

//折半插入排序

void  BInsertSort(int array[],size_t size){for (size_t i=1;i<size;i++){int tem=array[i];int low=0,high=i-1;while (low<=high){int m=(low+high)/2;if (tem<array[m]){high=m-1;}else low=m+1;}//whilefor (int j=i-1;j>=high+1;--j){array[j+1]=array[j];}array[high+1]=tem;}//for}     


//2-路插入排序

void TWayInsertSort(int array[],size_t size)  {    int first,final;    first=final=0;    int tem[size];    tem[0]=array[0];    for(int i=1;i<size;i++)    {        if(array[i]>=tem[final])        {            tem[++final]=array[i];        }        else if(array[i]<=tem[first])        {            first=(first-1+size)%size;            tem[first]=array[i];        }        else//進行折半插入排序,在網上看了很多人的這部分是直接插入的。        {            int low,high;            if(array[i]<tem[0])            {                low=first;                high=size-1;             }              else             {                 low=0;                 high=final;             }              int m;             while(low<=high)             {                 m=(low+high)/2;                 if(array[i]<tem[m])  high=m-1;                 else low=m+1;             }             for(int j=final;j!=high;j=(j-1+size)%size)             {                 tem[(j+1)%size]=tem[j];             }             tem[(high+1)%size]=array[i];              final++;           }//else}//forfor(int i=0,j=first;i<size;j=(j+1)%size,++i)array[i]=tem[j];}    

//2-路插入排序的另一個版本

void  BInsertSort(int array[],size_t size){for (size_t i=1;i<size;i++){int tem=array[i];int low=0,high=i-1;while (low<=high){int m=(low+high)/2;if (tem<array[m]){high=m-1;}else low=m+1;}//whilefor (int j=i-1;j>=high+1;--j){array[j+1]=array[j];}array[high+1]=tem;}//for}

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.