排序算法之折半插入排序

import java.util.*;

public class BinaryInsertSort {
    private static int[] Sort(int[] arr) {
        int i, j;
        //保存中间插入的值
        int insertNote = 0;
        //将待排序的数列保存起来
        int[] array = arr;
        System.out.println("开始排序:");
        for (i = 1; i < array.length; i++) {
            int low = 0;
            int high = i - 1;
            insertNote = array[i];
            //不断的折半
            while (low <= high) {
                //找出中间值
                int mid = (low + high) / 2;
                //如果大于中间值
                if (array[i] > array[mid]) {
                    //在大于中间值的那部分查找
                    low = mid+1;
                } else
                    //在小于中间值的那部分查找
                    high = mid-1;
            }
          //将整体数组向后移
            for ( j=i; j > low; j--) {
                array[j] = array[j - 1];
            }
         //插入到指定的位置
            array[low] = insertNote;
            System.out.println(Arrays.toString(array));
        }
        System.out.println("排序之后:");
        System.out.println(Arrays.toString(array));
        return array;
    }

    public static void main(String[] args) {
        Random random = new Random();
        int[] array = new int[10];
        for (int i = 0; i < 10; i++) {
            array[i] = Math.abs(random.nextInt() % 100);
        }
        System.out.println("排序之前:");
        System.out.println(Arrays.toString(array));            
        BinaryInsertSort.Sort(array);
    }
}
相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页