# 实现

 1 package algorithm.sort;
2
3 import java.util.Arrays;
4
5 public class BinaryInsertSortTest1 {
6     public static void main(String[] args) {
7         int[] arr1 = { 4, 7, 5, 6, 1, 3, 8 };
8         int[] arr2 = { 7, 6, 5, 4, 3, 2, 1 };
9         int[] arr3 = { 5, 9, 3, 7, 8, 6, 1, 2, 4 };
10         int[] arr4 = { 13, 2, 5, 4, 88, 76, 68, 87, 55, 88, 88, 77, 67, 99, 100, 5, 53, 52, 51, 66 };
11         sort(arr1);
12         sort(arr2);
13         sort(arr3);
14         sort(arr4);
15         System.out.println(Arrays.toString(arr1));
16         System.out.println(Arrays.toString(arr2));
17         System.out.println(Arrays.toString(arr3));
18         System.out.println(Arrays.toString(arr4));
19     }
20
21     public static void sort(int[] arr) {
22         for (int i = 1; i < arr.length; i++) {// 循环遍历数组,定第2个元素开始,只有1个元素的话不用排序
23             int value = arr[i];
24             int low = 0;
25             int mid = 0;
26             int high = i - 1;
27             while (low <= high) { // 2分法查找要插入的位置,终止条件是high=mid-1以后比low小.小于符号的满足条件的情况是high=low+1,mid=low,high=mid-1<low
28                 mid = (low + high) / 2;
29                 if (value > arr[mid]) { // 如果比mid大,下次查找的数组为mid的后半段
30                     low = mid + 1;
31                 } else { // 否则下次查找的数组为mid的前半段
32                     high = mid - 1;
33                 }
34             }
35             // value就应该放到low这个位置,所以把low之后的元素都向后移动一格
36             for (int j = i; j > low; j--) {
37                 arr[j] = arr[j - 1];
38             }
39             arr[low] = value;
40         }
41     }
42 }

posted @ 2017-03-08 17:00 abcwt112 阅读(...) 评论(...) 编辑 收藏