jeudi 5 septembre 2019

Binary Search algorithm to find minimu element

"I am trying to find the minimum element using the binary search
algorithm. In the lats two else if loops once tried without equal sign and with equal sign."

int Solution::findMin(const vector<int> &A) {

int low=0,high=A.size()-1;//low -lower index and high-last index



while(low<=high){

 //in case the array is sorted or array contains one element
if(A[low]<=A[high])return A[low];
else {

//to find the middle index

int mid=(low+high)/2;

//to check whether minimu element lies in the middle
if(A[mid-1]>A[mid]&&A[mid]<A[mid+1]){

    return A[mid];

  if( A[mid]>A[mid+1])return A[mid+1]; 
}


//to check the halve in which minimum element lies
else if(A[high]>=A[mid]){high=mid-1;}
else if(A[low]<=A[mid])low=mid+1;

}}




}

No error messages .I want to know what difference that '=' operator can make.

Aucun commentaire:

Enregistrer un commentaire