Willem Van Onsem's answer describes well the case where many queries will be made on the same array, so it's worth taking O(n log n) time to sort the array first. My answer doesn't directly address "unsorted arrays", but there is a common misconception that arrays either are unsorted or have been sorted, and I think it is worth addressing that misconception in case it helps any readers.
To be clear, I don't assume that you have this particular misconception; but I do think some people who have this misconception will read your question and its answers.
The word "sorted" is a bit misleading. Since "sorted" is a past tense verb, it makes it sound like a sorting algorithm has been used to put the data in order. But the way computer scientists use the word "sorted", it just means that the array is in order, without implying that it was previously not in order.
So when we say binary search can only be used on a "sorted array", that doesn't mean it took O(n log n) time to make the array "sorted". Lots of data is naturally in order without having to do any work to sort it. A few examples:
- Suppose I have an unsorted array of numbers, and I want to build a prefix sum array, which contains the cumulative sums starting from the beginning of the original array. If there are no negative numbers in the original array, then the cumulative sums will naturally be in ascending order.
- Suppose I have a sequence with some special elements, and I want to perform queries where, given an index, the query finds the first special element after that index. It would help to have a list of the indices in the sequence where the special elements occur; the natural way to find those indices would find them in ascending order.
- Suppose I want an array of the first
n
prime numbers, or all prime numbers less than or equal to n
. Almost any algorithm that solves either problem will generate the prime numbers in ascending order.
So in many cases, we can apply binary search without having to take O(n log n) time to sort the sequence that needs to be searched.