您的位置:首页 > 其它

折半插入排序

2016-06-08 22:03 176 查看
从直接插入排序的过程可以看出,在每趟直接插入排序的过程中,均在有序区寻找插入位置,因此可以采用折半查找的方法寻找插入位置,这就是折半插入排序。

折半插入排序与直接插入排序相比,紧减少了关键字之间的比较次数,而数据元素的移动次数不变,折半插入排序的时间复杂度仍未O(n2).

public class InsertSort {
/*使用折半插入法进行排序*/

public static void main(String[] args) {
int array[]=new int[]{9,8,7,6,5,4,3,2,1};  //把待排序的数存放在数组中
int i,j,temp;
int low,high,mid;
for(i=1;i<array.length;i++){//需要进行n-1趟插入排序
temp=array[i];
low=0;
high=i-1;

while(low<=high){  //折半查找插入位置
mid=(low+high)/2;
if(array[mid]>temp){
high=mid-1;
}else{
low=mid+1;
}
}

for(j=i-1;j>=low;j--){   //后移
array[j+1]=array[j];
}

array[low]=temp;  //插入
}

for(i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: