📜  顺序不可知的二进制搜索 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:36.803000             🧑  作者: Mango

代码示例1
/*
Order Agnostic Binary Search
-> works for both Ascending and Descending Order Sorted Arrays.
-> Returns the Index Value of the Element in the Array, if found.
-> -1, if not found.
*/

public class OrderAgnosticBinarySearch {

    public static int BinarySearch(int[] array, int element) {
        int a_pointer = 0;
        int b_pointer = array.length - 1;
        boolean isAscending = array[a_pointer] < array[b_pointer];

        if (array[a_pointer] == element) return a_pointer;
        else if (array[b_pointer] == element) return b_pointer;

        while (a_pointer <= b_pointer) {
            int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
            if (array[midpoint] == element) return midpoint;

            if (isAscending){
                if (array[midpoint] < element) a_pointer = midpoint + 1;
                else b_pointer = midpoint - 1;
            }
            else {
                if (array[midpoint] > element) a_pointer = midpoint + 1;
                else b_pointer = midpoint - 1;
            }
        }
        return -1;
    }
  
    public static void main(String[] args) {
        int[] list = {87, 63, 60, 54, 53, 51, 41, 36, 12, -1, -12};
        int[] list2 = {12, 15, 19, 27, 36, 45, 55, 69, 87, 90, 120};
        System.out.println(BinarySearch(list, -1)); // Output: 9
        System.out.println(BinarySearch(list2, 55)); // Output: 6
    }
}