Day 13 - Searching Algorithms
Basic Questions

Basic Questions

Find the Index of an Element in an Array

Code

Explanation

  1. The function linearSearch (or linear_search in Python) iterates through the array arr to find the element x.
  2. If the element is found, the function returns its index; otherwise, it returns -1.

Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Find an Element in a Sorted Array Using Binary Search

Code

Explanation

  1. The function binarySearch (or binary_search in Python) divides the array into halves and checks if the middle element is the target x.
  2. If x is less than the middle element, it searches the left half; if greater, it searches the right half.
  3. The process continues until the element is found or the search space is exhausted.

Analysis

  • Time Complexity: O(log n)
  • Space Complexity: O(1)

Note: Once you have understood the above examples, try to solve the following problems on your own.

Extra Problems

  1. Find the First and Last Position of an Element in a Sorted Array
  1. Find the Square Root of a Number Using Binary Search