折半插入排序演算法的C++實現

來源:互聯網
上載者:User

標籤:++   條件   iostream   log   依次   元素   否則   lin   nbsp   

折半插入排序思想和直接插入排序類似。

1)找到插入位置;

2)依次後移正確位置及後面的元素。

區別是尋找插入位置的方法不同。

折半插入排序使用的折半尋找法在一個已經有序的序列中找到尋找位置。

注意,折半尋找法的一個基本條件就是序列已經有序。

直接上代碼:

#include<iostream>using namespace std;void binaryInsertionSort(int arr[],int n){    int mid;    for(int i=1;i<n;i++){        int low=0,high=i-1;//將要插入的元素複製出來        int temp=arr[i];        //當low>high時,證明折半尋找結束        while(low<=high){            mid=(low+high)/2;            //每次和折半查到的元素比較大小            //當待插入元素比折半查到的元素小時,那麼正確插入位置在低半區;否則在高半區            if(arr[i]<arr[mid])                high=mid-1;            else                low=mid+1;    }        //由折半尋找到的正確插入位置為high+1        //將high+1後面的元素依次後移        for(int j=i-1;j>=high+1;j--)            arr[j+1]=arr[j];        //在正確位置插入複製出來的待插入元素        arr[high+1]=temp;    }    }int main(){    int a[10]={10,9,8,7,6,5,4,3,2,1};    binaryInsertionSort(a,10);    for(int i=0;i<10;i++){        cout<<a[i]<<" ";    }    cout<<endl;    return 0;}

 

折半插入排序演算法的C++實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.