Back to Articles

Searching Algorithms in an Array

Introduction to Searching Algorithms

Searching algorithms are fundamental to computer science. They help us find specific elements within a data structure efficiently.

In this article, we'll explore various searching algorithms used with arrays, their time complexities, and when to use each one.

1. Linear Search

Linear Search is the simplest searching algorithm. It checks each element sequentially until it finds the target or reaches the end.

Algorithm:

  1. Start from the first element
  2. Compare each element with the target
  3. If found, return the index
  4. If not found after checking all elements, return -1

Time Complexity:

  • Best Case: O(1) - Element found at first position
  • Average Case: O(n) - Element found in the middle
  • Worst Case: O(n) - Element not found or at the end

Space Complexity:

O(1) - No extra space required

2. Binary Search

Binary Search is an efficient algorithm for searching in sorted arrays. It works by repeatedly dividing the search interval in half.

Algorithm:

  1. Compare target with the middle element
  2. If target matches, return the index
  3. If target is greater, search the right half
  4. If target is smaller, search the left half
  5. Repeat until found or search space is empty

Time Complexity:

  • Best Case: O(1) - Element found at middle
  • Average Case: O(log n)
  • Worst Case: O(log n)

Space Complexity:

O(1) for iterative, O(log n) for recursive

Prerequisites:

The array must be sorted for binary search to work correctly.

3. Jump Search

Jump Search is a searching algorithm for sorted arrays. It jumps ahead by fixed steps and then performs linear search in the identified block.

Time Complexity:

O(√n) - Better than linear but worse than binary

4. Interpolation Search

Interpolation Search is an improvement over binary search for uniformly distributed sorted arrays. It uses the value of the target to estimate its position.

Time Complexity:

  • Average Case: O(log log n)
  • Worst Case: O(n)

Comparison Table

Algorithm Time Complexity Space Complexity Prerequisites
Linear Search O(n) O(1) None
Binary Search O(log n) O(1) Sorted array
Jump Search O(√n) O(1) Sorted array
Interpolation Search O(log log n) O(1) Sorted & uniformly distributed

When to Use Which?

  • Linear Search: Small arrays, unsorted data, or when simplicity is key
  • Binary Search: Large sorted arrays, when performance matters
  • Jump Search: Sorted arrays, when binary search is not feasible
  • Interpolation Search: Uniformly distributed sorted data