折半插入排序(C语言,严蔚敏教材改编)

原理:

严版教材P266-P277

天勤P237

代码:

#include 
#include 
#include 
#include 

void BInsertSort(int r[], int n)
{
	int i, j, low,high, m, temp;

	for (i = 1; i < n; ++i)
	{
		low = 0, high = i - 1;
		temp = r[i];
		while (low <= high)
		{
			m = (low + high) / 2;
			if (r[m] > temp)//这里为>,没有=,因为相等的时候插入到m的后一个位置即low处
				high = m - 1;
			else
				low = m + 1;
		}
		for (j = i - 1; j >= high + 1; --j)
		{
			r[j + 1] = r[j];//易错
		}
		r[high + 1] = temp;//不论是递增还是递减,永远插在high的后面一个
	}
}

int main()
{
	int r[8] = { 49,38,65,97,76,13,27,49 };
	int n = 8;
	BInsertSort(r, n);
	int i;
	for (i = 0; i < n; ++i)
	{
		printf("%d\t", r[i]);
	}
	system("pause");
	return 0;
}

 

你可能感兴趣的:(初试数据结构学习)