Hi, ive tried looking this up for confirmation, ive seen pages saying it works for sorted, but looking for confirmation that it only works for sorted strings. I am wondering if binary searches, only works for strings that have been sorted into an order. And does not work for strings in a random order?
It's just such a stupid question.
How could a binary search work on an unsorted array?
It's not magic.
It's a very simple procedure, and it obviously requires a sorted array.
binary search determines which half of a data structure holds your value. It does that because it is sorted, if you have 1,2,3,4,5,6,7 and you asked for 6, the middle value is 4. 6 > 4. 6 must be in the back half. It then searches 4,5,6,7 and so on, throwing away half each time until it finds it or shows it is not there at all.
now consider 1,7,6,2,3,4,5 ... looking for 6 again. Which half is it in? The computer sees 1,2,and 5 to make this choice, it does not see the whole array. What criteria do you have that tells you 6 is in the front half? Nothing.
There are other ways to search or sort data, if you cannot sort it as is. You can make a copy (simple data) or a light copy (heavy data, eg objects take a vector of pointers to them, sort the pointers by the data) if nothing else.