複習資料結構:排序(一)——插入排序,資料結構排序

來源:互聯網
上載者:User

複習資料結構:排序(一)——插入排序,資料結構排序

    

    從這一篇開始,我開始複習資料結構的知識點,博文主要偏重於每個知識點的核心思想,以及代碼實現。這一篇先從排序演算法中的插入排序開始。


    穩定排序、內排序、適合少量資料量的排序。
當輸入數組已經排好序時,插入排序需要O(n),快排需要O(n^2)。
當輸入數組倒序排列時,插入排序時複為:O(n^2)。
平均時間複雜度:O(n^2)。

插入排序的基本做法是:將一個數插入到一個已經排列好的數組中,通過移動這個數的位置,使得插入之後的數組也是有序的,不斷重複這個過程,使得最終所有的數都是有序的。


    實現代碼如下:

#include<iostream>using namespace std; void InsertSort(int a[], int n){for(int i = 1; i < n; i++){if(a[i] < a[i-1])  // a[i]是待排元素,前面i-1個數已經排序好{int j = i-1;  // 準備前移int x = a[i]; a[i] = a[i-1]; while(x < a[j]){a[j+1] = a[j]; j--; }a[j+1] = x; }}}int main(){int a[] = {2, 1, 5, 8, 4, 3}; InsertSort(a, 6); for(int i = 0; i< 6; i++)cout<<a[i]<<' '; cout<<endl; return 0; }






聯繫我們

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