0

i have this question where im given a an array that contains the distance of a traveler from a certain destination at the i-th time of the day. ideally the array should be in descending order but the array could contain mistakes where the traveler gets further from the destenation and i should find at which index does that mistake happen using binary search. heres the code i wrote:

int find_mistake(int dist[] , int n){
    int l = 0 , r = n-1 , mid;
    while(l<=r){
        mid = (l+r)/2;
        if (dist[mid] > dist[mid - 1]){
            return mid;
        }
        else if (dist[mid] > dist[l]){
            r = mid ;
        }
        else{
            l = mid ;
        }
}
return -1;

i would be glad if someone pointed mistakes in it as ive seen other solution and im not sure about mine.

  • 1
    We're not a coding site, so checking your code is likely outside the scope of this site. – D.W. Aug 29 '23 at 17:06

2 Answers2

1

You can't solve this by binary search !

That's because even if you know the values at the endpoints of an interval containing the inversion, looking at the central value doesn't hint you in which half the inversion is. In the worst case, you can't spare an $O(n)$ search.

0

Let’s say you have one hundred data points. They should be in ascending order, but one of them has been modified.

If you look at all but two data points, and you didn’t look at the wrong one, then you have no idea which of the two was incorrect. It could be either.

Even if you looked at all data points except one: Say you have five points with values 1000, 1100, unknown, 1300, 1400. The “unknown” one could be 1350, and you wouldn’t know if that is the wrong value or the next one at 1300.

gnasher729
  • 29,996
  • 34
  • 54