[3] 演算法之路 - 插入排序

來源:互聯網
上載者:User

標籤:演算法   插入排序   

插入排序 – 演算法

1、將排序部分分成兩部分

2、每次從後面部分取最前面的數插入到前面部分的適當位置


該處提供兩個插入排序版本,指定間隔插入與插入排序。後面對指定間隔排序提到Shell排序中的n/2間隔與Sedgewick間隔

例如:

排序前:92 77 67 8 6 84 55 85 43 67

[77 92] 67 8 6 8455 85 43 67 將77插入92前

[67 77 92] 8 6 8455 85 43 67 將67插入77前

[8 67 77 92] 6 8455 85 43 67 將8插入67前

[6 8 67 77 92] 8455 85 43 67 將6插入8前

[6 8 67 77 84 92]55 85 43 67 將84插入92前

[6 8 55 67 77 8492] 85 43 67 將55插入67前

[6 8 55 67 77 84 8592] 43 67 ......

[6 8 43 55 67 77 8485 92] 67 ......

[6 8 43 55 67 67 7784 85 92] ...... 


// 插入排序int InsertionSort(int a[],int lens){int k;int tmp;for(int i=1;i<lens;i++){int j=i-1;//取出待插資料tmp = a[i];// 遍曆前面已排好序的序列,找插入位置// 在i之前尋找需待插入資料a[i]的位置kfor(k=j;k>=0;k--){if(tmp<a[k]) a[k+1]=a[k];// 後移else break;//找到位置}// 找到位置,插入指定值if(i!=(k+1))a[k+1]=tmp;}return 0;}// 插入排序 - 使用指定間隔的int InsertionSortWithGap(int a[],int lens,int gap){int k,tmp;// 控制插入層for(int m=0;m<gap;m++){for(int i=gap+m;i<lens;i+=gap){int j=i-gap;tmp=a[i];for(k=j;k>=0;k-=gap){if(tmp<a[k]) a[k+gap]=a[k];else break;}if(i!=(k+gap))a[k+gap]=tmp;}}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.