Binary Search Flashcards
1
Q
Binary Search algorithm - Recursion O( logn)
A
int binarySearch(ll a[],ll low,ll high,ll k) { if(low>high) return -1;
int mid = (low+high)/2; if(a[mid]==k) return mid;
if(a[mid]>k) return binarySearch(a,low,mid-1,k);
return binarySearch(a,mid+1,high,k); }
2
Q
Binary Search algorithm - Iterative O( logn)
A
int binarySearch(ll a[],ll low,ll high,ll k) { while(low<=high) { int mid = (low+high)/2;
if(a[mid]==k) return mid; else if(a[mid]>k) high=mid-1; else low=mid+1; } return -1; }