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; }
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;
}
+ 1
Martin Taylor It's a good programming exercise. And it can improve understanding of the algorithm.
0
Large array means large number of elements and its working for key 6.
0
If array is sorted in descending order binary search should work?