为什么binarySearch需要一个排序数组? [英] Why binarySearch needs a sorted array?

查看:531
本文介绍了为什么binarySearch需要一个排序数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果binarySearch方法要求您在将数组作为参数传递给方法调用之前对其进行排序,为什么不在binarySearch方法中进行排序?

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需要一个排序数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆