插入排序

1、算法原理

插入排序是最簡單的一種排序算法。插入排序由N-1趟排序組成。對於P=1趟到P=N-1趟,插入排序保證從位置0到位置P上的元素爲已排序狀態。插入排序利用了這樣的事實:位置0到位置P-1上的元素是已排序的。


2、代碼(C版)

/*+++++++++++++++++++++++++++++++++++++++++++++
+	插入排序(C版)
+
+
+author:zhouyongxyz		2013-4-14 16:57
++++++++++++++++++++++++++++++++++++++++++*/
#include <cstdio>

#define N 9
typedef int ElementType;

void InsertSort(ElementType a[],int n);

int main()
{
	int a[N]={4,2,1,3,5,6,8,9,7};
	InsertSort(a,N);
	for(int i=0;i<N;i++)
		printf("%d ",a[i]);
	printf("\n");
	return 0;
}

void InsertSort(ElementType a[],int n)
{
	int i,P;
	int tmp;
	for(P=1;P<n;P++)
	{
		tmp=a[P];
		for(i=P;i>0&&tmp<a[i-1];i--)
				a[i]=a[i-1];
		a[i]=tmp;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章