If binarySearch method requires you to sort your array before passing it as parameter to the method call, why not do a sort in the binarySearch method?
Binary search works by assuming the middle of the array contains the median value in the array. If it is not sorted, this assumption does not make sense, since the median can be anywhere and cutting the array in half could mean that you cut off the number you were searching for.
Binary search works only on a sorted set of elements. To use binary search on a collection, the collection must first be sorted. When binary search is used to perform operations on a sorted set, the number of iterations can always be reduced on the basis of the value that is being searched.
Now, the question arises, is Binary Search applicable on unsorted arrays? So, the answer is NO, it is not possible to use or implement Binary Search on unsorted arrays or lists, because, the repeated targeting of the mid element of one half depends on the sorted order of data structure.
No, binary search needs a sorted array. You might have other properties of an array that enables you to make a search that is more efficient than a mere iteration but the very nature of binary search necessitates sorted data.
Binary search works by assuming the middle of the array contains the median value in the array. If it is not sorted, this assumption does not make sense, since the median can be anywhere and cutting the array in half could mean that you cut off the number you were searching for.
The reason binary search does not do the sort itself is because it does not need to...the array is already sorted.
It is generally considered good programming practice to define functions that focus on one goal. This leads to more modular, reusable code and avoids code repitition.
For example, it would be advisable to implement a function that does the sorting for you and which you can then simply call in different search functions. This way, you do not have to repeat the sorting code in every search function you want to implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With