Home >Java >javaTutorial >Binary search under Java programming

Binary search under Java programming

高洛峰
高洛峰Original
2016-12-19 16:16:021014browse

Algorithm: This method is suitable when the amount of data is large. When using binary search, the data must be in order and not repeated. Basic idea: Assume that the data is sorted in ascending order. For a given value x, start the comparison from the middle position of the sequence. If the current position value is equal to x, the search is successful; if x is less than the current position value, then in the first half of the sequence Search; if x is greater than the current position value, continue searching in the second half of the sequence until it is found.

Suppose there is an array { 12, 23, 34, 45, 56, 67, 77, 89, 90 }. Now it is required to use the binary method to find the specified value and return it at the index of the array. If it is not found, return -1. The code is as follows:

package cn.sunzn.dichotomy;

public class DichotomySearch {
   public static void main(String[] args) {
       int[] arr = new int[] { 12, 23, 34, 45, 56, 67, 77, 89, 90 };
       System.out.println(search(arr, 12));
       System.out.println(search(arr, 45));
       System.out.println(search(arr, 67));
       System.out.println(search(arr, 89));
       System.out.println(search(arr, 99));
   }

   public static int search(int[] arr, int key) {
       int start = 0;
       int end = arr.length - 1;
       while (start <= end) {
           int middle = (start + end) / 2;
           if (key < arr[middle]) {
               end = middle - 1;
           } else if (key > arr[middle]) {
               start = middle + 1;
           } else {
               return middle;
           }
       }
       return -1;
   }
}



For more articles related to binary search in Java programming, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn