小蚂蚁学习数据结构(35)——直接插入排序

直接插入排序

    在已经形成的有序表中线性查找,并在适当位置插入,把原来位置上的元素向后顺移。

时间效率:最坏的情况是 n^2

空间效率:1,因为仅仅占用一个缓冲单元

算法的稳定性:稳定。

# include <stdio.h>

int insertSort( int * a, int n )
{
	int i, t, j;
	
	for( i = 1; i < n; ++i )
	{
		t = a[i];
		
		for( j = i - 1; j > -1 && a[j] > t; --j )
		{
			a[j+1] = a[j];
			a[j] = t;
		}
	}
	
	return 0;
}

int main( void )
{
	int i;
	int a[] = { 50, 40, 60, 30, 70, 20, 80 };
	insertSort( a, 7 );
	
	for( i = 0; i < 7; ++i )
	{
		printf( "%d ", a[i] );
	}
	
	printf( "\n" );
	
	return 0;
}


学PHP的小蚂蚁 博客 http://my.oschina.net/woshixiaomayi/blog


你可能感兴趣的:(直接插入排序)