数据结构--加入二分查找的插入排序(优化)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33621967/article/details/52971400
package cn.hncu.binary;

import java.util.Scanner;

public class BinarySort {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数组的长度:");
        int len = sc.nextInt();
        //申明定义一个数组
        int[] a = new int[len];
        //给数组中的每个值进行赋值
        System.out.println("给数组中的每个数进行赋值操作:");
        for(int i=0;i<a.length;i++){
            a[i] = sc.nextInt();
        }
        //给数组进行排序操作
        binary(a);
        for(int x:a){
            System.out.print(x+" ");
        }
    }

    private static void binary(int[] a) {
        //优化后的选择排序---带二分的选择排序
        for(int i=0;i<a.length-1;i++){//排序的趟数
            //带插入(等待排序)的数
            int temp = a[i+1];
            //二分
            int low = 0;
            int high = i;//最大的数为第i个数,数组本身是有序的
            int mid;
            while(low<=high){//进行排序操作
                mid = (low+high)/2;//找出中间数的位置来跟待插入的数进行比较
                if(a[mid]>temp){
                    //把中间的数赋值给给high(即最大的数),缩小比较范围---优化的地方
                    high = mid-1;//优化!
                }else{//否则的话将中间的数赋值给最小的数
                    low = mid+1;
                }
            }
            //上面这段代码只是找到带插入入的位置!

            //经过上面的比较可以得出low=high+1
            //将数组中的位置进行移位,给待插入的数腾一个位置(这里应该注意一个小细节!移位时注意从后往前挪!这样不会导致数据被前面的数据给覆盖掉!)
            for(int j=i;j>high;j--){
                a[j+1] = a[j];//往后挪位置
            }

            //将待插入的数插入到数组中
            a[high+1] = temp;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33621967/article/details/52971400