排序算法:折半插入排序

折半插入排序(Binary Sort)

一、算法思路

二、算法流程

三、算法实现

#include
using namespace std;
typedef int KeyType;

struct ElemType
{
	KeyType key;
	int exist;
};

struct SeqList
{
	ElemType *elem;
	int length;
};

void BinarySort(SeqList &L)
{
	int a, b, m;
	ElemType x;
	for(int i = 1; i < L.length; i++)
	{
		x = L.elem[i];
		a = 0;
		b = i-1; 
		while(a <= b)
		{
			m = (a+b)/2;
			if(L.elem[m].key > x.key)
				b = m-1;
			else
				a = m+1;
		}
		for(int j = i-1; j > b; j--)
		{
			L.elem[j+1].key = L.elem[j].key;
		}
		L.elem[b+1].key = x.key;
	}
}

int main()
{
	ElemType test[] = { {4},{6},{2},{7},{5},{1},{3},{8} };
	SeqList L;
	L.elem = test;
	L.length = 8;
	BinarySort(L);
	for (int i = 0; i < L.length; i++)
	{
		cout << L.elem[i].key << endl;
	}
	return 0;
}

四、算法复杂度分析

时间复杂度为 O ( n 2 ) O(n^2) O(n2)
空间复杂度为 O ( 1 ) O(1) O(1)

五、相关练习题

你可能感兴趣的:(排序算法,算法,数据结构)