1.说一下什么是二分法?使用二分法时需要注意什么?如何用代码实现?
二分法查找(Binary Search)也称折半查找,是指当每次查询时,将数据分为前后两部分,再用中值和待搜索的值进行比较,如果搜索的值大于中值,则使用同样的方式(二分法)向后搜索,反之则向前搜索,直到搜索结束为止。
二分法使用的时候需要注意:二分法只适用于有序的数据,也就是说,数据必须是从小到大,或是从大到小排序的。
public class Lesson7_4 {public static void main(String[] args) {// 二分法查找int[] binaryNums = {1, 6, 15, 18, 27, 50};int findValue = 27;int binaryResult = binarySearch(binaryNums, 0, binaryNums.length - 1, findValue);System.out.println("元素第一次出现的位置(从0开始):" + binaryResult);}/*** 二分查找,返回该值第一次出现的位置(下标从 0 开始)* @param nums 查询数组* @param start 开始下标* @param end 结束下标* @param findValue 要查找的值* @return int*/private static int binarySearch(int[] n