c/c++插入排序

插入排序是低級排序中比較快的一種,原理是,將數據分爲內外兩部分,內部初始爲一個數據,將外部數據插入內部,插入的原則是比後面的小,比前面的大。



代碼如下(c編寫)

#include<stdio.h>
void insertionsort(int *a,int n);
void main()
{
	int a[10]={7,2,1,3,6,5,0,9,8,4};
	int j;
	insertionsort(a,10);
	for(j=0;j<10;j++)
	{
		printf("%d\n",a[j]);
	}
}

void insertionsort(int *a,int n)
{
	int in,out,temp;
	for(out=1;out<n;out++)
	{	
		temp=a[out];
		in=out;
		while(in>0 && a[in-1]>=temp)
		{
			a[in]=a[in-1];
			in--;
		}
		a[in]=temp;
	}
}


發佈了28 篇原創文章 · 獲贊 35 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章