Understand Binary Search Problem

🚀 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

Java
Output:

Loading component...

Loading component...