[JAVA] Binary search binary search method

Binary search binary search method

Search method to search while narrowing the range in half


Search speed is fast


Data needs to be sorted in advance


class BinarySerch{
  public static void main(String[] args){
   //Sorted array to search
   int a[] = {1,3,6,8,10};
   //Value to search
   int serchValue = 3;
   //The sequence number of the found data The initial value is an error value (-1)
   int find = -1;

   //Leftmost and rightmost numbers to search
   int left = 0;
   int right = a.length-1;
   //Repeat when there is data on the left and right edges to check
   while(left <= right){
     //Specify the position to check the number in the middle of the left and right
     int middle = (int)((left + right)/2);
     //Compare the value of the position to look for with the position to look for
     if(a[middle] == serchValue){
        //If they are the same, save the number and end the iteration
        find = middle;
    }else if (a[middle] < serchValue){
    //If it is smaller than the value you are looking for, move the left edge
     left = middle + 1;
    }else {
    //If it is larger than the value you are looking for, move the right edge
    right = middle - 1;
  //Display search results
  System.out.println("search results:" + find);

Reference book [Enjoyable learning algorithm and programming pictorial book](https://www.amazon.co.jp/%E6%A5%BD%E3%81%97%E3%81%8F%E5%AD%A6%E3%81] % B6-% E3% 82% A2% E3% 83% AB% E3% 82% B4% E3% 83% AA% E3% 82% BA% E3% 83% A0% E3% 81% A8% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0% E3% 81% AE% E5% 9B% B3% E9% 91% 91-% E6% A3% AE-% E5% B7% A7% E5% B0% 9A-ebook / dp / B01N56TW48)

Recommended Posts

Binary search binary search method
Binary search method
Practice of binary search method
Method to search
Arbitrary search method in an array using binary search
Practice of linear search method
[Ruby] Search problem using index method
to_i method
java (method)
getRequestDispatcher () method
merge method
A story about writing a binary search method at an in-house study session
Map method
I tried to solve AOJ's Binary Search
include method
Abstract method
initialize method
List method
puts method
Linear search
Java method
Class method
save! method
getParameter method
[Java] method
[Rails] Method summary for conversion / verification / search
private method
rails method
Binary tree memorandum for beginners (Part 5 Binary search tree)
[Java] method
Introduction to algorithms with java-Search (Full search, Binary search)
Implement the algorithm in Ruby: Day 3 -Binary search-
Binary tree memorandum for beginners (Part 2 Search for binary trees)