日期:2014-05-16  浏览次数:20647 次

递归实现插入排序,算法导论练习2.3,linux C实现

采用递归实现插入排序,代码简洁,linux下纯C实现,编译通过,核心函数如下:

void sort(int* a, int index, int N)
{
	int key = *(a + index);
	int i = index - 1;
	if(index+1 <= N)
	{
		for(;i>=0;i--)
			if(key >= *(a+i))
				break;
			else
				*(a+i+1) = *(a+i);
		*(a+i+1) = key;
		index = index + 1;
		sort(a, index, N);
	}
	return;
}

完整代码如下:

#include <stdio.h>
void sort(int* a, int index, int N)
{
	int key = *(a + index);
	int i = index - 1;
	if(index+1 <= N)
	{
		for(;i>=0;i--)
			if(key >= *(a+i))
				break;
			else
				*(a+i+1) = *(a+i);
		*(a+i+1) = key;
		index = index + 1;
		sort(a, index, N);
	}
	return;
}
int main()
{
	int sequence[10] = {56,4,76,18,34,12,24,16,38,1};
	int L = sizeof(sequence)/sizeof(int);
	int i = 0;
	sort(sequence, 1, L);
	for(;i<L;i++)
	{
		printf("%d ", sequence[i]);
	}
	printf("\n");
	return 0;
}