Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Binary Search
- // Date : 17.10.19
- #include<iostream>
- using namespace std;
- int binarySearch(int arr[], int n, int key){
- int first = 0, last = n-1, mid = (first + last) / 2;
- while(first <= last && arr[mid] != key){
- if(arr[mid] < key){
- first = mid + 1;
- }
- else if(arr[mid] > key){
- last = mid - 1;
- }
- mid = (first + last) / 2;
- }
- if(arr[mid] == key) return mid;
- else return -1;
- }
- int main(){
- int n;
- cout << "Enter the range of array: "; cin >> n;
- int arr[n], i;
- cout << "Enter the element of array: ";
- for(i = 0; i < n; i++){
- cin >> arr[i];
- }
- for(i = 0; i < n-1; i++){
- if(arr[i] > arr[i+1]){
- cout << "The array is not sorted and the binary search only works in a sorted array." << endl;
- return 0;
- }
- }
- cout << "Enter the element to search: ";
- int key; cin >> key;
- int isPresent = binarySearch(arr, n, key);
- if(isPresent == -1) cout << "The element is not present" << endl;
- else cout << "The element is present at " << isPresent << " position." << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment