Why binarySearch needs a sorted array?

我只是一个虾纸丫 提交于 2019-12-01 06:08:20

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.

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