使用二分查找在有序数组里面查找元素

返回所有跟所求值匹配的元素下标

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 22, 22,444, 534, 1000};
        List<Integer> resultIndex = binarySearch(arr, 0, arr.length - 1, 22);
        System.out.println(resultIndex);
    }

    /**
     * @param arr       数组
     * @param left      左边索引
     * @param right     右边索引
     * @param findValue 要查找的值
     * @return
     */
    public static List<Integer> binarySearch(int[] arr, int left, int right, int findValue) {

        int mid = (left + right) / 2; // 中间索引
        int midValue = arr[mid];

        if (left > right) {
            return new ArrayList<>();
        }
        if (findValue > midValue) { //向右递归
            return binarySearch(arr, mid + 1, right, findValue);
        } else if (findValue < midValue) {
            return binarySearch(arr, left, mid - 1, findValue);
        } else {
            List<Integer> resultIndex = new ArrayList<Integer>();

            //向mid索引值的左边扫描,将所有满足所求值的数的下标,加入到集合中
            int temp = mid - 1;
            while (true) {
                if (temp < 0 || arr[temp] != findValue) {
                    break;
                }
                resultIndex.add(temp);
                temp--;
            }
            resultIndex.add(mid);

            //向右扫描,将所有满足所求值的数的下标,加入到集合中
            temp = mid + 1;
            while (true) {
                if (temp > arr.length - 1 || arr[temp] != findValue) {
                    break;
                }
                resultIndex.add(temp);
                temp++;
            }
            return resultIndex;
        }


    }
}

猜你喜欢

转载自blog.csdn.net/qq_41890624/article/details/107791442