Searching Algorithms
|
Linear Search – Unsorted Input
Time Complexity: O(n). As we need to traverse the complete array in worst case. Worst case is when your desired element is at the last position of the array. Here, ‘n’ is the size of the array. Space Complexity: O(1). No extra memory is used to allocate the array. |
Linear Search – Sorted
Time Complexity: O(n). As we need to traverse the complete array in worst case. Worst case is when your desired element is at the last position of the sorted array. However, in the average case this algorithm is more efficient even though the growth rate is same as unsorted. Space Complexity: O(1). No extra memory is used to allocate the array. |
Binary Search
Time Complexity: O(logn). We always take half input and throwing out the other half. So the recurrencerelation for binary search is T(n) = T(n/2) + c. Using master theorem (divide and conquer), we get T(n) =O(logn) Space Complexity: O(1) |