30: Implement binary search in a sorted array.
⏳⌚ 00:00:00

Question:-

Implement binary search in a sorted array.
Example 1:
Input:
N=6, target = 3
arr[] = {5, 8, 3, 15, 19, 22}
Output: 2nd index
Example 1:
Input:
N=6, target = 9
arr[] = {5, 8, 3, 15, 19, 22}
Output: Not found

Steps to solve:-

1. Function binarySearch:- The binarySearch function takes several parameters: =>
the sorted integer array arr[], the left index left, the right index right, and the target element target.
It performs binary search iteratively, dividing the search range in half in each iteration until the target element is found or the search range is empty.
If the middle element equals the target, it returns the index of the middle element as the result.
If the middle element is smaller than the target, it narrows the search range to the right half by updating left.
If the middle element is larger than the target, it narrows the search range to the left half by updating right.
If the target element is not found, it returns -1 to indicate that the target is not in the array.
2. Main Function:- In the main function: The user inputs two values: n (the number of elements in the array) and target (the element to search for). An integer array arr of size n is declared to store the input elements. The user inputs n elements into the array. The binarySearch function is called with the given array, search range (0 to n-1), and the target element. The result of the binary search is displayed, indicating whether the target element was found and at which index.

solution->

View Code 1
Time Complexity = O(log(N))
Space Complexity = O(1)