【模板小程式】二分法插入排序

來源:互聯網
上載者:User

標籤:using   val   vector   nbsp   std   bin   排序   array   sort   

Java版來源程式來自:http://www.cnblogs.com/PerkinsZhu/p/5674572.html,在此感謝。

 1 #include <iostream> 2 #include <vector> 3 #include <string> 4 using namespace std; 5  6 void printArray(string str,vector<int>& array){ 7     cout<<str; 8     for(int val:array){ 9         cout<<val<<" ";10     }11     cout<<endl;12 }13 14 void binaryInsertionSort(vector<int>& array) {15     printArray("原數組:", array);16     int time=0;17     for (int i = 1; i < (int)array.size(); ++i) {18         int temp = array[i];19         int right = i - 1;20         int left = 0;21         int mid;22         // 定位23         while (left <= right) {24             //mid = (left + right) / 2;25             mid = left+(right-left)/2;26             if (array[mid] > temp) {27                 right = mid - 1;28             } else if (array[mid] < temp) {29                 left = mid + 1;30             }31         }32         // 移動數組33         for (int j = i; j > left; j--) {34             array[j] = array[j - 1];35         }36         // 在找到的位置插入37         array[left] = temp;38         printArray("第" + to_string(++time) + "次迴圈排序結果: ", array);39     }40 }41 42 int main()43 {44     vector<int> v={21,8,2,18,0,9,27,12,5,24};45     binaryInsertionSort(v);46     return 0;47 }

運行結果:

原數組:21 8 2 18 0 9 27 12 5 24
第1次迴圈排序結果: 8 21 2 18 0 9 27 12 5 24
第2次迴圈排序結果: 2 8 21 18 0 9 27 12 5 24
第3次迴圈排序結果: 2 8 18 21 0 9 27 12 5 24
第4次迴圈排序結果: 0 2 8 18 21 9 27 12 5 24
第5次迴圈排序結果: 0 2 8 9 18 21 27 12 5 24
第6次迴圈排序結果: 0 2 8 9 18 21 27 12 5 24
第7次迴圈排序結果: 0 2 8 9 12 18 21 27 5 24
第8次迴圈排序結果: 0 2 5 8 9 12 18 21 27 24
第9次迴圈排序結果: 0 2 5 8 9 12 18 21 24 27

 

二分尋找就是把插入位置的尋找過程由原來的順序尋找改成了二分尋找,效率很高。

【模板小程式】二分法插入排序

聯繫我們

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