public class BinaryInsertionSort {
public BinaryInsertionSort(int a[],int length)
{
int temp=0;//哨兵
for(int i=1;i<length;i++) //每个元素依次插入排序
{
int low=0;
int high=i-1;
int j=0;
temp=a[i];
while (high>=low) //折半查找要插入的元素的位置。这里注意取等号
{
int m=(high+low)/2;
if(temp<a[m])
high=m-1;
else if(temp>a[m])
low=m+1;
else
{
high=m;
break;
}
}
for(int p=i;p>high+1;p--) //移动元素的位置
{
a[p]=a[p-1];
}
a[high+1]=temp;
}
}
public static void main(String[] args) {
int a[] = new int[100];
for (int i = 0; i < a.length; i++) //产生0-10001的数组
a[i]=(int)(Math.random()*1000+1);
//int a[] = {1, 6, 23,21};
new BinaryInsertionSort(a, a.length);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
折半插入排序算法是一种稳定的排序算法,比直接插入算法明显减少了关键字之间比较的次数,因此速度比直接插入排序算法快,但记录移动的次数没有变,所以折半插入排序算法的时间复杂度仍然为O(n^2),与直接插入排序算法相同。附加空间O(1)。
折半查找只是减少了比较次数,但是元素的移动次数不变,所以时间复杂度为O(n^2)是正确的!