Binary search method, implemented in java

1. Introduction

Binary search is another common search method for lists of logarithmic values. The prerequisite for using binary search is that the elements in the array must have been sorted. Assume that the array has been sorted in ascending order. The binary search method first compares the key with the middle element of the array. Consider the following three situations:

  • If the key is less than the middle € element, you only need to continue to search for the key in the first half of the elements of the array.
  • If the keyword and the middle element are equal, the match is successful and the search ends.
  • If the key is greater than the middle element, you only need to continue to search for the key in the second half of the array.

2. Code

package com.zhuo.base;

public class BinarySearch {
    
    
    public static void main(String[] args) {
    
    
        int [] list = {
    
    2,4,7,10,11,45,50,59,60,66,69,70,79};
        int i = binarySearch(list,2);
        int j = binarySearch(list, 11);
        int k = binarySearch(list, 12);
        int l = binarySearch(list, 1);
        int m = binarySearch(list, 3);
        System.out.println(i);
        System.out.println(j);
        System.out.println(k);
        System.out.println(l);
        System.out.println(m);
    }
    public static int binarySearch(int[] list, int key) {
    
    
        int low = 0;
        int high = list.length - 1;
        while (high >= low) {
    
    
            int mid = (low + high) / 2;
            if (key < list[mid])
                high = mid - 1;
            else if (key == list[mid])
                return mid;
            else
                low = mid + 1;
        }
        return -low - 1;
    }
}

Three. Results display

0
4
-6
-1
-2

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113702413