Search code examples
arraysalgorithmsearchdata-structuresbinary-search

Is knowledge of sorting order of given array pre-requisite for implementing binary search?


I am relatively new to data structures and algorithms and while learning about the nuances of binary search I noticed that almost every solution assumes an array sorted in ascending order and hence their solutions wont work for test cases with input array sorted in descending order.

So I was wondering whether is it a pre-requisite to mention the sorting order in the problem statement or should I go with a generalised approach that runs for both ascending and descending order?

Any help/suggestions would be appreciated. Thanks.


Solution

  • You need to know about the order of sorting (whether it is ascending or descending) before binary searching.

    Assuming you have a binary search implementation that works for ascending order, but your array is in descending order. You can simply reverse the array and do a binary search on it.