Binary search Program in java
Explanation:
- The function binarySearch takes an integer array arr and an integer x as input and returns the index of x in arr if it is present. If not, it returns -1.
- The variables left and right are initialized to 0 and arr.length-1, respectively, to represent the lower and upper bounds of the search space.
- In each iteration of the while loop, mid is calculated as the average of left and right.
- If arr[mid] is equal to x, the function returns mid.
- If arr[mid] is less than x, the search space is updated to the right of mid by setting left to mid + 1.
- If arr[mid] is greater than x, the search space is updated to the left of mid by setting right to mid - 1.
- The while loop continues until left is greater than right or x is found. If x is not found, the function returns -1.
- In the main method, the array arr and the search value x are defined, and the result of the binarySearch function is stored in result.
- If result is -1, the program outputs that the element is not present. Otherwise, it outputs the index at which the element was found.
Java Stream Binary Search Algorithm
0 comments:
If you have any doubts,please let me know