折半插入排序算法
很多情况下需要用到一些基础的排序算法,接下来分析折半插入排序算法:
1.待排序数组a分为两个区间,一个是已经安排好排序的子区间b,另外一个时当前数组未排序部分c;
2.将c中首元素在b中有序序列进行二分查找其位置,,找到合适位置插入;
3.数组c不为空时循环操作2;
一、构图分析:
二、 代码实现:
#include<iostream>
#include<iomanip>
using namespace std;
typedef char KeyType;//自定义需要排序数组类型
void halfInsertQueue(KeyType R[],int n)
{
int i;
int j;
int high;
int low;
int mid;
KeyType temp;
for( i = 1; i < n; i++ )//初始将数组a从R[0]与R[1]之间分开为有序序列b与剩余待插入序列c两部分
{
temp = R[i];
low = 0;
high = i - 1;
while(high >= low) //二分查找有序序列b,找到c中待插入元素位置后插入
{
mid = (high + low)/2;
if(temp > mid)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
for( j = i - 1; j >= high + 1; j-- )//将查找位置后的元素依次后移一位
R[j+1] = R[j];
R[high+1] = temp;
}
cout<<"用折半插入排序算法得到序列:"<<endl;
for( i = 0; i < n; i++ )
cout<<setw(5)<<R[i];//格式输出
}
int main()
{
char a[4]={'a','b','c','d'};
halfInsertQueue(a,4);
return 0;
}
三、算法分析:
有序序列b较大时,相较于直接插入性能更好,平均性能更好。
时间复杂度:o(n^2)
空间复杂度:o(1)