1. 程式人生 > >修改插入排序,將順序查詢改為二分查詢

修改插入排序,將順序查詢改為二分查詢

#include<iostream>
using namespace std ;
void InsertSort(int *a,int n){
	int r,l,m,temp;
	for(int i=1;i<n;i++){
		temp=a[i];
		l=0;
		r=i-1;
		while(l<=r){
			m=(l+r)>>1;
			if(a[m]<temp) l=m+1;
			else r=m-1;
		}
		for(int j=i-1;j>=l;j--)
			a[j+1]=a[j];
		a[l]=temp;
	}	
	for(int i=0;i<n;i++)
		cout << a[i] << " " ;
}
int main()
{
	int a[9]={9,3,2,5,4,1,7,4,14};
	InsertSort(a,9);
	return 0;
}