Java binary search algorithm of the classic (dichotomy)

When using dichotomy, the data should not be ordered and repetitive

And a child playing guessing game is the same, will let you guess a number between 1 and 100 he thought, when you guess a number, he will tell you three choices of a, than he wanted big or small, or guessed, in order to use the least number of guessed, must start from 50 guess, if you guess a little, then you have to start guessing from 51 to 100, so the next time guess is 75 (half of 51 to 100), but if he says a little big, that the introduction of a number between 1 and 49, so the next time 25 guess, guess time will each possible value into two parts

Thought achieved: assume that the data is in ascending order, to a given value x, from the intermediate position to find the start sequence, when the value of x is less than the current position, is searched in the first half of the sequence, and then the data is divided into two

If the position x is larger than the current value, the lookup in the second half of the sequence, then the data is divided into two

If the current position value equals x, then return directly returns -1 if it is not found

Implementation code:

public class Half {
 
    public static void main(String[] args) {
        int[] arr = new int[]{12, 23, 34, 45, 56, 67, 77, 89, 90};//length:9
        System.out.println(search(arr, 34));
 
    }
 
    public static int search(int[] arr, int key) {
        int start = 0;
        int end = arr.length - 1;//8
        while (start <= end) {
            int middle = (start + end) / 2;//中间值:4,1,2
            if (key < arr[middle]) {
                end = middle - 1;
            } else if (key > arr[middle]) {
                start = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}

//输出2

 

Guess you like

Origin www.cnblogs.com/zouwangblog/p/10984916.html