#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Searching Algorithms

Binary Search in Data Structure

Binary Search is a searching algorithm that finds the position of a target value within a sorted array by repeatedly dividing the search range in half.

Algorithm Steps

  • Compare the target with the middle element of the array.
  • If they match, the search is complete.
  • If the target is smaller, repeat the search on the left half.
  • If the target is larger, repeat the search on the right half.
  • Repeat until the target is found or the search range is empty.
def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

def binary_search_recursive(arr, target, low, high):
    if low > high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        return binary_search_recursive(arr, target, mid + 1, high)
    else:
        return binary_search_recursive(arr, target, low, mid - 1)

Complexity

CaseTimeSpace (iterative)
BestO(1)O(1)
Average/WorstO(log n)O(1)

Applications

  • Searching in sorted databases and indexes.
  • Finding the boundary in problems like 'first/last occurrence' or 'search in rotated sorted array'.
  • Used in library functions like Python's bisect module.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course