插入法排序

來源:互聯網
上載者:User

標籤:style   color   2014   io   for   re   

    所謂插入排序法,就是檢查第i個數字,如果在它的左邊的數字比它大,進行交換,這個動作一直繼續下去,直到這個數位左邊數字比它還要小,就可以停止了。

    假設我們輸入的是 “5,1,4,2,3” 我們從第二個數字開始,這個數字是1,我們的任務只要看看1有沒有正確的位置,我們的做法是和這個數字左邊的數字來比,因此我們比較1和5,1比5小,所以我們就交換1和5,原來的排列就變成了“1,5,4,2,3 ”

    接下來,我們看第3個數字有沒有在正確的位置。這個數字是4,它的左邊數字是5,4比5小,所以我們將4和5交換,排列變成了 “1,4,5,2,3 "我們必須繼續看4有沒有在正確的位置,4的左邊是1,1比4小,4就維持不動了。

/**********************************************************************  *功能描述:插入法排序  *輸入參數: 數組, 起始索引(0), 終止索引 *輸出參數: 排好序的數組 *傳回值: void *其它說明:  *修改記錄1:   //修改記錄,包括修改日期、版本號碼、修改人及修改內容等  *修改日期        版本號碼              修改人         修改內容  * --------------------------------------------------------------------------------------------------  * 20140716         V1.0              wuyq            建立  ***********************************************************************/ void insertion_sort(int array[], int first, int last){int i,j;int temp;for(i=first+1; i<=last; i++){temp=array[i];j=i-1;//與已排序的數逐一比較,大於temp時,該數移後while((j>=first)&&(array[j]>temp)){array[j+1]=array[j];j--;}array[j+1]=temp;}}/**********************************************************************  *功能描述:插入法排序  *輸入參數: 數組, 元素個數 *輸出參數: 排好序的數組 *傳回值: void *其它說明:  *修改記錄1:   //修改記錄,包括修改日期、版本號碼、修改人及修改內容等  *修改日期        版本號碼              修改人         修改內容  * --------------------------------------------------------------------------------------------------  * 20140716         V1.0              wuyq            建立  ***********************************************************************/ void insert_sort(int* array, unsigned int n){int i,j;int temp;for(i=1;i<n;i++){temp=*(array+i);for(j=i;j>0&&*(array+j-1)>temp;j--){*(array+j)=*(array+j-1);}*(array+j)=temp;}}#include <stdio.h>int main(){int a[8] = {5, 6, 2, 7, 2, 0, 1, 4};//insertion_sort(a, 0, 7);insert_sort(a, 8);int i;for(i=0; i<8; i++){printf("%d ", a[i]);}printf("\n");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.