Find the gender and ceil of the number X from an array that is already sorted. eg.
a [] = {3, 7, 9, 10, 15}
- if X = 2, floor = N / A, ceil = 3
- if X = 3, floor = 3, ceil = 3
- if X = 4, floor = 3, ceil = 7
- if X = 16, floor = 15, ceil = N / A
I think most of us are aware of the solution, that is, we can find the floor / ceil by a modified binary search. But the problem with the modified binary search is that we need to take care of a lot of boundary conditions. But I found that the same binary search algorithm works, but for gender we just need to write if low > high return low
and for ceil if low > high return high
. And if floor return -1 shows N / A, and if ceil returns a value that is larger than the array index than show N / A.
algo for the floor:
int floorSearch(int a[], int low, int high, int x) { if(low > high){ return low; } int mid = (low+high)/2; if(a[mid]>x){ return floorSearch(a, low, mid-1, x); } else if(a[mid]<x){ return floorSearch(a, mid+1, high, x); } else{ return mid; } }
and for ceil:
int ceilSearch(int a[], int low, int high, int x) { if(low > high){ return high; } int mid = (low+high)/2; if(a[mid]>x){ return ceilSearch(a, low, mid-1, x); } else if(a[mid]<x){ return ceilSearch(a, mid+1, high, x); } else{ return mid; } }
It is very simple, right? I checked a lot of inputs and it works, but I could not prove the correctness of the algorithm. Can someone give him an attempt to prove the correctness, or you can also give a sample input for which this algo will fail. Thanks.
source share