二分插入法与直接排序类似,只是在确定插入位置的方法是用二分法,即从第0个数据开始依次折半与待插入的数据进行比较直到找到合适的位置。
2、图示:
![](http://dl2.iteye.com/upload/attachment/0113/1140/95942789-2032-3249-b6a7-b8fdde77dd1f.png)
3、Java具体代码实现:
package com.leiht.sort; public class SortBinary { public static void main(String[] args) { int[] numbers = { 56, 45, 78, 67, 99, 13, 34, 49, 55, 34, 12, 77, 1 }; System.out.println("排序之前:"); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } new SortBinary().sortBinary(numbers); System.out.println(); System.out.println("排序之后:"); for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } } private void sortBinary(int[] numbers) { for(int i = 0; i < numbers.length; i++) { int temp = numbers[i]; int left = 0; int right = i -1; int middle = 0; while(left <= right) { middle = (left + right)/2; if(numbers[i] > numbers[middle]) { left = middle+1; }else { right = middle-1; } } for(int j = i-1; j >= left; j--) { numbers[j+1] = numbers[j]; } numbers[left] = temp; System.out.println("left=" + left + ",right=" + right + ",middle=" + middle); } } }
4、分析
显然,二分排序是一种稳定的排序方法