Binary search with duplicates and return 1st occrance idx of duplicate element.
Answer:
1: Treat find 1st occrance idx of duplicate element as natural case.
//*****Better******but cost more recursive steps!!*****//
int BSHelp1(int a[], int low, int high, int val){
while( low < high){
int mid = low + (high-low)/2;
if( val > a[mid]){
low = mid + 1; //+1, to avoid infinite loop!!!
}
else{ //if(val <= a[mid]). Note: if(val==a[mid],still recursive into the left part to search for 1st idx!!!
high = mid;
}
}
//low == high now.
if(val == a[low]) return low;
else return -1;
}
int BS1 (int a[],int n, int val){
return BSHelp1(a,0,n-1,val);
}
int BSHelp2(int a[], int low, int high, int val){
while(low < high){
int mid = low +(high-low)/2;
if(val == a[mid]) {
//Just add while loop part.
int idx = mid;
while(a[idx] == a[idx-1]){
--idx;
}
return idx; //Find the 1st idx of duplicate value.
}
else if(val < a[mid]){
high = mid;
}
else{
low = mid + 1;
}
}
//edge case: low == high now!
if(val == a[low]) return low;
else return -1; //don't exist in the array!
}
Test function:
int main(){
int arr[] ={-100,-100,-2,-2,0,3,5,5,9,9,15,15,15,19,22,22,22,23,24,24,26,50,50,105,105,160};
int len = sizeof(arr)/sizeof(int);
for (int i=0; i<len;++i){
cout<< arr[i]<< ' ';
}
cout <<endl;
int value;
cout<<"Input the value you want to search:"<<endl;
int index;
while(cin>>value){
if(value == -111111) break; //Quit!
index = BS1(arr,len,value);
cout<<"Index is:"<<index<<endl;
cout<<"Input the value you want to search:"<<endl;
}
return 0;
}
No comments:
Post a Comment