Use while instead of using recursive in C++ (#19320)
This commit is contained in:
committed by
Todd Chaffee
parent
1920b0b4fa
commit
619f955faa
@ -181,14 +181,13 @@ int binarySearch(int a[], int l, int r, int x) {
|
|||||||
```C++
|
```C++
|
||||||
int binary_search(int arr[], int l, int r, int target)
|
int binary_search(int arr[], int l, int r, int target)
|
||||||
{
|
{
|
||||||
if (r >= l)
|
while (r >= l)
|
||||||
{
|
{
|
||||||
int mid = l + (r - l)/2;
|
int mid = l + (r - l)/2;
|
||||||
if (arr[mid] == target)
|
if (arr[mid] == target)
|
||||||
return mid;
|
return mid;
|
||||||
if (arr[mid] > target)
|
if (arr[mid] > target) r = mid - 1;
|
||||||
return binary_search(arr, l, mid-1, target);
|
else l = mid + 1;
|
||||||
return binary_search(arr, mid+1, r, target);
|
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user