Answer to Question #246380 in C for gryffin

Question #246380

[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.


1
Expert's answer
2021-10-04T07:51:34-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS