折半插入算法 稳定排序算法



时间复杂度o(nlogn)
#include <iostream> 
#include <cstdio> 
#include <math.h>
#include <cstdlib> 

using namespace std; 

const int n = 40; 

void swap(int *a,int i,int j) 

int temp; 
temp = a[i]; 
a[i] = a[j]; 
a[j] = temp; 


int binarysearch(int * a,int n,int value) 

int m,l,d;
m = 0;
l = n - 1;
while(m <= l)
{
d = static_cast<int>((m+l)/2);
if(a[d] == value) return d;   //找到,插在d前面
else if(a[d] < value)m = d+1;
else l = d-1;
}
return m;                            //未找到,插在m前面

}

void binaryinsertsort(int * a,int n) 
{     
int k,temp;
for(int i = 1;i < n;i++)
{
k = binarysearch(a,i,a[i]);
temp = a[i];
for(int j =i-1;j >= k; j-- )a[j+1] = a[j];
a[k] = temp;
}


void printarray(int * a,int n) 

cout << "print array "
<< endl;
for(int i = 0;i < n;i++)
{
cout << a[i]
<< "  ";
if((i+1)%10 == 0)
cout << endl;
}
cout << endl;


int main(int argc,char *argv[]) 

int a[n];

for(int i = 0;i < n;i++)
a[i] = rand()%1000;
printarray(a,n);
binaryinsertsort(a,n);
printarray(a,n);

return 0;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值