[JAVA] Binary search method

I had the opportunity to write a 2-minute search, so I will write it as a memo.

What is a 2-minute search? The algorithm used when searching for data. You can continue the search while narrowing down the range of sorted data. A method for searching at high speed.

The 2-minute search is just an algorithm that searches while narrowing down the range by half from the entire array. Fast.

Sample.java



int algorithm(int[] data, int target) {
    int retrieve = -1;
    int left = 0;
    int right = data.length - 1;
   
    while(left < right){
        int mid = (left + right)/ 2;
        if(data[mid] == target){
            return mid + 1;
        }else if(target < data[mid]){
            return right = mid;
        }else {
            return left = mid + 1;
        }
    }
    return retrieve;
}

Summary If it's already sorted, it's better to do a 2-minute search.

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
Method
Practice of linear search method
[Ruby] Search problem using index method
Java method
to_i method
java (method)
getRequestDispatcher () method
A story about writing a binary search method at an in-house study session
Map method
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)