[Binary search and overflow] Write a program with a function that performs binary
search. Assume that the elements of the array are unsigned integers, and the following
elements are present along with other elements in the array: 4294967290, 4294967295,
10400.
#include<iostream>
using namespace std;
int binary_search(unsigned int arr[], int n, int size, unsigned int k){
if (size >= n){
int middle = n + (size - n) / 2;
if(arr[middle] == k)
return middle;
if(arr[middle] > k)
return binary_search(arr, n, middle - 1, k);
else
return binary_search(arr, middle + 1, size, k);
}
return -1;
}
int main(){
int row, col;
cout<<"Enter the array size:- ";
cin>>row;
unsigned int arr[row], s;
cout<<" Enter the array elements:- ";
for(int i = 0; i < row; i++)
cin>>arr[i];
cout<<"\nEnter a number to search:- ";
cin>>s;
col = binary_search(arr, 0, row-1, s);
if(col == -1)
cout<<"Element not found";
else
cout<<"Element located "<<col+1;
return 0;
}
Comments
Leave a comment