0

Is this Binary Search working for long Array ?

is this binary search program will run without problem ? please reply in comment #include<iostream> using namespace std; void binarysearch(int arr[],int size,int key){ int st=0,mid,last=size-1,cnt=0; while(st<last){ mid=(st+last)/2; //cout<<cnt++<<" "; // to check how mant times loop run if(arr[mid]==key) { cout<<"found"; return; } if(arr[mid]>key && arr[st]<key){ last=mid; }else{ st=mid; } } cout<<"not found"; } int main(){ int arr[]={1,2,3,4,5,6,7,8,9}; int arr_size=sizeof(arr)/sizeof(arr[0]); int key=6; binarysearch(arr,arr_size,key); return 0; }

6th Jan 2022, 3:13 PM
Prakriti Maiti
7 Respuestas
0
#include<iostream> using namespace std; void binarysearch(int arr[],int size,int key){ int st=0,mid,last=size-1,cnt=0; while(st<last){ mid=(st+last)/2; cout<<cnt++<<" ";// to check how mant times loop run if(arr[mid]==key) { cout<<"found"; return; } if(arr[mid]>key && arr[st]<key){ last=mid; }else{ st=mid; } } cout<<"not found"; } int main(){ int arr[]={1,2,3,4,5,6,7,8,9}; int arr_size=sizeof(arr)/sizeof(arr[0]); int key=6; binarysearch(arr,arr_size,key); return 0; }
6th Jan 2022, 3:14 PM
Prakriti Maiti
+ 1
Martin Taylor It's a good programming exercise. And it can improve understanding of the algorithm.
6th Jan 2022, 7:43 PM
Simon Sauter
Simon Sauter - avatar
0
Large array means large number of elements and its working for key 6.
6th Jan 2022, 3:37 PM
Prakriti Maiti
0
If array is sorted in descending order binary search should work?
6th Jan 2022, 3:38 PM
Prakriti Maiti