折半插入排序(binary insertion sort)是对插入排序算法的一种改进,所谓排序算法过程,就是不断的依次将元素插入前面已排好序的序列中。
在将一个新元素插入已排好序的数组的过程中,寻找插入点时,将待插入区域的首元素设置为a[low],末元素设置为a[high],则轮比较时将待插入元素与a[m],其中m=(low+high)/2相比较,如果比参考元素小,则选择a[low]到a[m-1]为新的插入区域(即high=m-1),否则选择a[m+1]到a[high]为新的插入区域(即low=m+1),如此直至low<=high不成立,即将此位置之后所有元素后移一位,并将新元素插入a[high+1]。
来源:百度百科:http://baike.baidu.com/link?url=9_rUozR9Pu5uqs0EZD0ogq5wqQbp0cRL_-_phPf8tGqgOKSspiXAmyw1j3sH8D7_v5fL9rakdnsXBh5Ux0pl2JDY3jWWx_-gDoxo9-Nv_ngdexJGcC0RVgc34z3XU1gNkWB8jqsWRAD3EOJ5UbFo7q
code:
package test;
import java.util.Scanner;
public class test {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int [] a=new int[10];
for(int i=0;i<10;i++)
a[i]=input.nextInt();
for (int i=1;i<10;i++)
{
int low=0;
int high=i-1;
int t=a[i];
int center=(low+high)/2;
while(low<=high)
{
center=(low+high)/2;
if (a[i]<a[center]){
high=center-1;//边界的时候要注意,不然会出现死循环的现象
}
else{
low=center+1;
}
}
System.out.println();
for(int j=i;j>low;j--)
a[j]=a[j-1];
a[low]=t;//这一步的赋值也要注意
for(int j=0;j<10;j++)
System.out.print(a[j]+" ");
System.out.println();
}
}
}