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.
The reason binary search does not do the sort itself is because it does not need to...the array is already sorted.
binarySearch
method doesn't do the sorting itself. –
Predigestion 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.
© 2022 - 2024 — McMap. All rights reserved.