Understand Binary Search Problem

Problem Name: Binary Search
Problem Description:

🚀 Binary Search Algorithm Explained

Binary Search is an efficient algorithm for locating a target element in a sorted array by repeatedly dividing the search interval in half.


Steps

  1. Initialize Pointers:
    Set left to the start of the array and right to the end.
  2. Calculate the Middle:
    Compute the middle index using:
    mid = left + (right - left) / 2;
    
  3. Compare and Conquer
    • Target Found:
      If the element at mid equals the target, return mid (target found).
    • Search Right Half:
      If the element at mid is less than the target, update left to mid + 1 to search the right half.
    • Search Left Half:
      If the element at mid is greater than the target, update right to mid - 1 to search the left half.

4.Repeat

  • Continue steps 2 and 3 until the target is found or left exceeds right.
  • If the target is not found, return -1.

Time Complexity

ScenarioTime ComplexityExplanation
Best CaseO(1)The target is found at the middle in the first try.
Average CaseO(log n)The search space is halved with each iteration.
Worst CaseO(log n)Even in the worst case, the number of comparisons grows logarithmically.
Category:
  • Searching & Sorting
Programming Language:
  • Java
Reference Link:

https://drawtocode.vercel.app/problems/binary-search

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

INPUT: [1,2,3,4,5] ,3

OUTPUT: 2

public static void main(String args[]){

int arr[] = { 1,2,3,4,5 };

int ans = binarySearch( arr,5);

if (ans == -1) {

System.out.print("Element is not present in array");

}//If End

else {

System.out.print("Element is present at index " + ans );

}//Else End

}//function end

Helper Function:

public static int binarySearch(int[] arr, int target) {

int left = 0;

int right = arr.length - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (arr[mid] == target) {

return mid;

}//If End

else{

if (arr[mid] < target) {

left = mid + 1;

}//If End

else {

right = mid - 1;

}//Else End

}//Else End

}//Loop End

return -1;

} //function end

Utility Functions and Global variables:

Utility Function is not required.