Osama Aref Osama Aref - 21 days ago 6
C++ Question

I want a recursive function to check the order of an array using binary search

I wrote a recursive function to check an array of size n if it's in ascending order:

bool sortedAscending(const int*x, int n){
if (n == 0) return true;
if (x[n - 1] >= x[n - 2]) sortedAscending(x, n - 1);
else return false;
}


I want to do the same job but using the binary search algorithm (i.e. splitting the array in half each recursive call..). How can i do that?
Thank you.

Answer
bool sortedAscending(const int* x, int n) {
  if (n <= 1) return true;
  int m = n / 2;
  return x[m-1] <= x[m] &&
         sortedAscending(x, m) &&
         sortedAscending(x + m, n - m);
}