二分排序算法是直接排序算法的一个优化,在每次插入的时候不是顺序查找了
而是利用前面的已经是有序数列的性质使用二分查找方式找到下一个插入的元素的位置。
public static void sort(int []a)
{
int temple,n=a.length;
for(int i=1;i<n;i++)
{
temple=a[i];
int j=find(i,a,temple);
for(int t=i-1;t>=j;t--)
{
a[t+1]=a[t];
}
a[j]=temple;
System.out.println(temple+" * "+Arrays.toString(a));
}
}
public static int find(int i,int[] a,int temple)
{
int low=0,high=i-1,middle=(low+high)/2;
if(high==0)
{
if(temple<a[high])
{
return 0;
}
}
while(low<=high)
{
if(a[middle]>temple)
{
high=middle-1;
middle=(low+high)/2;
}
else if(a[middle]<temple)
{
low=middle+1;
middle=(low+high)/2;
}
else
{
return middle+1;
}
}
return low;
}