Bisection Search Algorithm for java Algorithms

Binary search, also known as half-fold search, is a more efficient search method.,
The algorithm idea of the fold-and-half search is: to arrange the columns in an ordered (increasing or decreasing) order and to perform the fold-and-half search.It can significantly reduce the number of comparisons and improve the search efficiency.
Advantages: fewer searches and comparisons, fast searches and good performance.
Disadvantages: Require the lookup table to be ordered and difficult to insert and delete.

public static void main(String[] args) {
        int srcArray[] = {1, 3, 4, 5, 7, 8, 9, 10, 11, 17, 21, 23, 28, 30, 32, 38, 41, 47, 50, 56, 64, 78, 81, 88, 95, 98};
        System.out.println("Recursive implementation of binary lookup   " + searchValue(srcArray, 0, srcArray.length - 1, 47));
        System.out.println("Binary Find Ordinary Loop Implementation   " + searchValue(srcArray, 47));
    }

    //Recursive implementation of binary lookup
    public static int searchValue(int srcArray[], int start, int end, int key) {

        int mId = (end - start) / 2 + start;

        if (srcArray[mId] == key) {
            return mId;
        }

        if (start >= end) {
            return -1;
        } else if (key > srcArray[mId]) {
            return searchValue(srcArray, mId + 1, end, key);
        } else if (start >= end) {
            return searchValue(srcArray, start, mId - 1, key);
        }

        return 0;
    }

    //Binary Find Ordinary Loop Implementation
    public static int searchValue(int srcArray[], int key) {

        int mId = srcArray.length / 2;

        if (srcArray[mId] == key) {
            return mId;
        }
        int start = 0;
        int end = srcArray.length - 1;

        while (start <= end) {
            mId = (end - start) / 2 + start;
            if (key < srcArray[mId]) {
                end = mId - 1;
            } else if (key > srcArray[mId]) {
                start = mId + 1;
            } else {
                return mId;
            }
        }

        return 0;
    }

Posted by quercus on Sun, 08 Dec 2019 05:47:13 -0800