算法 - 二分查找/折半查找

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * 二分查找/折半查找
 */
public class BinarySearch {
    /**
     * 二分查找/折半查找
     * 数组必须为有序数组,且为升序
     * @param array
     * @param searchKey
     * @param low
     * @param high
     * @return
     */
    public static int search(int[] array, int searchKey, int low, int high) {
        // 判断素组是否为升序数组,不是则排序
        if (low == 0 && !isAscOrder(array)) {
            QuickSort.sort(array, low, high);
            System.out.println(Arrays.toString(array));
        }

        // 判定searchKey是否在数组范围内
        if (array[low] > searchKey || array[high] < searchKey) {
            return -1;
        }

        int middle = (low + high) / 2;
        // array[middle]正好是要查询的searchKey,直接返回middle
        if (array[middle] == searchKey) {
            return middle;
        }
        // array[middle]大于searchKey从左边查询
        else if (array[middle] > searchKey) {
            return search(array, searchKey, low, middle - 1);
        }
        // array[middle]小于searchKey从右边查询
        return search(array, searchKey, middle + 1, high);
    }

    /**
     * 判断数组是否为升序
     * @param array
     * @return
     */
    public static boolean isAscOrder(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i+1]) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[] array = generateArray(10);
        int index = search(array, 3, 0, array.length - 1);
        if (index == -1) {
            System.out.println("search key is not in array: " + index);
        } else {
            System.out.println("search key in array, index at: " + index);
        }
    }

    /**
     * 生成随机数组
     * @param length
     * @return
     */
    private static int[] generateArray(int length) {
        Random random = new Random(31);
        int[] array = new int[length];
        Set<Integer> set = new HashSet<>(length);
        for (int i = 0; i < length; i++) {
            int value;
            do {
                value = random.nextInt(length);
            } while (set.contains(value));
            array[i] = value;
            set.add(value);
        }
        return array;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值