Basic Questions
Find the Index of an Element in an Array
Code
Explanation
- The function
linearSearch
(orlinear_search
in Python) iterates through the arrayarr
to find the elementx
. - 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
- The function
binarySearch
(orbinary_search
in Python) divides the array into halves and checks if the middle element is the targetx
. - If
x
is less than the middle element, it searches the left half; if greater, it searches the right half. - 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
- Find the First and Last Position of an Element in a Sorted Array
- Find the Square Root of a Number Using Binary Search