Summary
We are using a binary search algorithm to find the target element ‘k’ in a sorted array ‘arr’.
Assuming:
Method: ‘binarysearch’
Array: ‘arr’
Solution
// User function template for C++ class Solution { public: int binarysearch(int arr[], int n, int k) { int s=0; int l= n-1;
int ans=-1;
while(s<=l){
int c = (s+l)/2;
if(arr[c] == k){ return c; }
else if(arr[c] > k){ l=c-1; } else{ s=c+1; } }
return ans; } }; |
Explanation
The intended element, k. If the target element is located, it returns its index; if not, it returns -1.
The variables s and l stand for the search range's start and end indices, respectively. At first, the array's start, s, is set to 0, and its end, l, is set to n - 1.
If the target element cannot be located, ans will return -1, which is its initial value.
Answered by:> >mritunjay_2
Credit:> >GeekforGeeks
Suggested blogs:
>How to detect whether the linked list has a loop using Java
>How to determine the number of valid groupings for a string using Java
>How to mock a constant value in Python?
>Creating a pivot table by 6 month interval rather than year
>How to Install mariaDB client efficiently inside docker?
>Can I call an API to find out the random seed in Python `hash()` function?
>How remove residual lines after merge two regions using Geopandas in python?