Skip to content

tanimul/Binary_Search

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Binary Search

Add a Binary search using JAVA language.

About Binary Search

Binary search is an efficient algorithm for finding an item from a sorted list of items. It is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer.Binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of item is returned. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero.

binary_search

Java

Step 1:

Binary search works on sorted arrays. So, sorted the array if arrays will unsorted.

Step 2:

We have to use the below formula to calculate the mid of the array -

 mid = (start + end) / 2;

Step 3:

     while (start <= end) {
        if (numbers[mid] < value) {
            start = mid + 1;
        } else if (numbers[mid] == value) {
            System.out.println(value + " is found at index: " + mid);
            break;
        } else {
            end = mid - 1;
        }
        mid = (start + end) / 2;
    }
    if (start > end) {
        System.out.println("Element not found!");
    }

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages