Java折半插入排序

折半插入排序是对直接插入排序的改进算法,又称为二分法插入排序,折半搜索要比顺序搜索快,所以就平均性能来说要比直接插入排序快,下面附上代码

import java.util.Scanner;
import org.junit.Test;
public class Main2 {
    /**
     * 折半插入排序
     * @param a 待排序数组
     * @return  排好序数组
     */
    public static int[] binaryInsertSort(int[] a) {
        int left = 0;// 数组左边界下标
        int right = a.length - 1;// 数组右边界下标

        for (int i = left + 1; i <= right; i++) {
            int temp = a[i];
            int low = left;
            int middle;
            int high = i - 1;// low到high为排好序区间

            while (low <= high) {// 利用折半搜索插入位置
                middle = (low + high) / 2;// 取中点
                if (temp < a[middle]) {// 插入值小于中点值
                    high = middle - 1;// 向左缩小区间
                } else {
                    low = middle + 1;// 向右缩小区间
                }
            }

            for (int k = i - 1; k >= low; k--) {// 成块移动,空出插入位置
                a[k + 1] = a[k];
            }

            a[low] = temp;// low即为插入位置
        }

        return a;
    }

    @Test
    public void testBinaryInsertSort() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数组长度!");
        int n = sc.nextInt();
        int[] a = new int[n];
        System.out.println("请输入数组元素");
        for (int i = 0; i < a.length; i++) {
            a[i] = sc.nextInt();
        }
        int[] result = binaryInsertSort(a);
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i] + " ");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36442947/article/details/80781290