Binary Search where the data is ordered in descending order.

I got an assignment for my class to modify the Binary Search where the data is ordered in descending order. But I can't figure out how I'm supposed to modify it.
.
Here's my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
int BinarySearch (int A[], int X, int low, int high)
{  
      bool found = false;
      int i, middle;
      while ((low <= high) && (!found))  {
         middle = (low + high)/2;
         if (X == A[middle]) {found = true;}
         else if (X < A[middle]) {high = middle-1;}
         else {low = middle+1;}
     }
     if (found) {return middle;}
     else {return -1;}
}
int main ()
{
int A [5]= {1,2,3,4,5};
cout<<BinarySearch(A,4,0,4);
cout<<endl;
cout<<BinarySearch(A,10,0,4);
    return 0;
}

Last edited on
(After changing your sample data to be ordered descending) there is only ONE line in your code where you compare data for non-equality against an interval position - change that.

Note that, for descending order, you may confuse yourself less if you rename the ends of the interval as left and right, rather than low and high.
Last edited on
Topic archived. No new replies allowed.