To implement a program to search an element in a list using binary search technique.
This program implements the binary search algorithm to find the index of a given element 'x' in a sorted array 'arr'.
The binary search algorithm works by repeatedly dividing the search interval in half until the target element is found or the search interval is empty. At each step, the algorithm compares the middle element of the current search interval with the target element 'x'. If they match, the algorithm returns the index of the middle element. If the middle element is greater than the target element, the search interval is divided into the lower half, and the search continues in that half. If the middle element is smaller than the target element, the search interval is divided into the upper half, and the search continues in that half. The process repeats until the target element is found or the search interval is empty.
In this implementation, the binary_search() function takes the input array 'arr', the indices of the lower and upper bounds of the search interval, and the target element 'x'. The function first checks if the search interval is not empty, i.e., if the 'high' index is greater than or equal to the 'low' index. If the search interval is not empty, the function calculates the middle index of the search interval using integer division. If the middle element is equal to the target element 'x', the function returns the index of the middle element. If the middle element is greater than the target element 'x', the function calls itself recursively with the lower half of the search interval, i.e., the 'low' index and 'mid-1'. If the middle element is smaller than the target element 'x', the function calls itself recursively with the upper half of the search interval, i.e., the 'mid+1' and 'high' index. The recursion continues until the target element is found, or the search interval is empty, in which case the function returns -1.
Finally, the program calls the binary_search() function with the input array 'arr', the indices of the lower and upper bounds of the search interval, and the target element 'x'. If the binary_search() function returns an index other than -1, the program prints the message "Element is present at index" followed by the index of the target element in the input array. Otherwise, the program prints the message "Element is not present in array".
By learning the Divide and Conquer algorithm to find the maximum value of an array, you can achieve several learning outcomes, including: