Why binarySearch needs a sorted array?

瘦欲@ 提交于 2019-12-30 09:36:34

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27512011/why-binarysearch-needs-a-sorted-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!