Edifecs interview question

Design an algorithm to efficiently search for a target element in a reverse-sorted array. Implement a function that takes the reverse-sorted array and the target value as inputs, returning the index of the target if found, or -1 if the target is not present in the array. Optimize the solution for time complexity.

Interview Answer

Anonymous

Aug 3, 2023

Initialize the left pointer to 0 and the right pointer to the last index of the array. While the left pointer is less than or equal to the right pointer: a. Calculate the middle index as (left + right) / 2. b. If the middle element is equal to the target value, return the middle index. c. If the middle element is greater than the target, update the left pointer to middle + 1. d. If the middle element is less than the target, update the right pointer to middle - 1. If the loop terminates without finding the target, return -1 to indicate that the target is not present in the array.