算法實(shí)現(xiàn):
使用插入排序?qū)⑾旅娴臄?shù)字按照從小到大的順序排列

步驟1:數(shù)組中已經(jīng)排好的是{1},將9插入數(shù)組中

步驟2:數(shù)組中已經(jīng)排好的是{2,9},將5插入數(shù)組中

步驟3:數(shù)組中已經(jīng)排好的是{2,5,9},將4插入數(shù)組中

步驟4:數(shù)組中已經(jīng)排好的是{2,4,,5,9},將8插入數(shù)組中

步驟5:數(shù)組中已經(jīng)排好的是{2,4,,5,8,9},將1插入數(shù)組中

步驟6:數(shù)組中已經(jīng)排好的是{1,2,4,,5,8,9},將6插入數(shù)組中

步驟7:排序完成

程序代碼:
#include <stdio.h> #include <stdlib.h> //插入排序 void InsertSort(int *a,int len); //輸出數(shù)組中的元素 void OutputArray(int *a, int len); void main() { int a[7] = {2, 9, 5, 4, 8, 1, 6}; //輸出數(shù)組中的元素 printf("排序前的數(shù)據(jù):"); OutputArray(a,7); //插入排序 InsertSort(a,7); //輸出排序后的結(jié)果 printf("排序后的數(shù)據(jù):"); OutputArray(a,7); system("pause"); } //插入排序 void InsertSort(int *a,int len) { for(int i=1;i<len;i++) { int j=i-1; int temp=a[i];//需要插入的數(shù)據(jù) while(temp<a[j] && j>=0)//當(dāng)插入的數(shù)據(jù)小于前面的數(shù)據(jù)時(shí) { a[j+1]=a[j];//將插入的數(shù)據(jù)的前面的數(shù)據(jù)向后移動(dòng) j--; } a[++j]=temp;//插入數(shù)據(jù) } } //輸出數(shù)組中的元素 void OutputArray(int *a, int len) { for(int i=0; i<len; i++) { printf("%d ",a[i]); } printf("/n"); } 執(zhí)行結(jié)果::

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選