Skip to content
Home ยป Binary Search in an Ordered Array

Binary Search in an Ordered Array


๐Ÿ“˜ Binary Search in an Ordered Array

1๏ธโƒฃ Introduction

Binary Search is an efficient searching algorithm used to find an element in a sorted (ordered) array.

It works by repeatedly dividing the search space into two halves.


2๏ธโƒฃ Precondition

โœ” The array must be sorted (ascending or descending)


3๏ธโƒฃ Working Principle

  • Find the middle element
  • Compare it with the target (key)
  • If equal โ†’ element found
  • If key < middle โ†’ search in left half
  • If key > middle โ†’ search in right half

Repeat until:

  • Element is found OR
  • Search space becomes empty

4๏ธโƒฃ Algorithm (Iterative Binary Search)

๐Ÿ”น Pseudocode

BinarySearch(A, n, key):
   low = 0
   high = n - 1

   while low <= high:
       mid = (low + high) / 2

       if A[mid] == key:
           return mid

       else if key < A[mid]:
           high = mid - 1

       else:
           low = mid + 1

   return -1   // element not found

5๏ธโƒฃ Example (Step-by-Step)

๐Ÿ”น Given Array (Sorted):

A = [2, 5, 8, 12, 16, 23, 38, 56]

๐Ÿ”น Search Key = 23


๐Ÿ”น Step 1

low = 0, high = 7
mid = 3 โ†’ A[3] = 12

23 > 12 โ†’ Search right half


๐Ÿ”น Step 2

low = 4, high = 7
mid = 5 โ†’ A[5] = 23

โœ” Element found at index 5


6๏ธโƒฃ Time Complexity

CaseComplexity
Best CaseO(1)
Average CaseO(log n)
Worst CaseO(log n)

๐Ÿ‘‰ Each step reduces problem size by half.


7๏ธโƒฃ Space Complexity

  • Iterative version โ†’ O(1)
  • Recursive version โ†’ O(log n) (stack space)

8๏ธโƒฃ Characteristics of Binary Search

โœ” Very efficient for large datasets
โœ” Requires sorted data
โœ” Reduces search space by half each step


9๏ธโƒฃ Advantages

  • Fast searching (logarithmic time)
  • Suitable for large data
  • Fewer comparisons

๐Ÿ”Ÿ Disadvantages

  • Works only on sorted arrays
  • Not suitable for dynamic data (frequent insert/delete)
  • Requires random access (not suitable for linked lists)

1๏ธโƒฃ1๏ธโƒฃ Comparison: Linear Search vs Binary Search

FeatureLinear SearchBinary Search
RequirementUnsorted OKMust be sorted
Time ComplexityO(n)O(log n)
EfficiencyLowHigh

๐Ÿ”š Conclusion

Binary Search is one of the most efficient searching algorithms for sorted data.

It works by dividing the search space into halves, leading to logarithmic time complexity.


๐Ÿ“Œ Exam Tip

๐Ÿ‘‰ Always mention:

  • Sorted array condition
  • Algorithm steps
  • Example
  • Complexity