-
-
Notifications
You must be signed in to change notification settings - Fork 362
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1922 from ranganeeraj/patch-10
Binary Search Using Divide and Conquer
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
Data Structure/Array Or Vector/Binary Search/SolutionByNeeraj.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
#include <iostream> | ||
#include <ctime> | ||
using namespace std; | ||
|
||
|
||
int getRandom(int x, int y) { | ||
srand(time(NULL)); | ||
return (x + rand() % (y-x+1)); | ||
} | ||
|
||
int binarySearch(int* arr, int low, int high, int key) { | ||
if (high >= low) { | ||
int mid = getRandom(low, high); | ||
if (arr[mid] == key) { | ||
return mid; | ||
} | ||
if (arr[mid] > key) { | ||
return binarySearch(arr, low, mid-1, key); | ||
} | ||
return binarySearch(arr, mid+1, high, key; | ||
} | ||
return -1; | ||
} | ||
|
||
int main() { | ||
int n; | ||
cout << "\nEnter Size\t: "; | ||
cin >> n; | ||
int arr[n]; | ||
cout << "\nEnter Elements "; | ||
for(int i =0; i < n; i++ ) { | ||
cin >> arr[i]; | ||
} | ||
int key; | ||
cout << "\nEnter key to be search\t: "; | ||
cin >> key; | ||
int temp = binarySearch(arr,0,n-1,key); | ||
if( temp == -1 ) { | ||
cout << "\nKey not Found\n"; | ||
} | ||
else { | ||
cout << "\nKey Found at " << temp << " Position\n"; | ||
} | ||
return 0; | ||
} |