二分法查找的关键是根据数组中间索引进行不断的二分来实现对数据的查找,注意此处数组必须为有序数组,示例代码如下:
- public class BinarySearch {
-
-
-
-
- public static int search(int[] nums, int num) {
- int minIndex = 0;
- int maxInde = nums.length - 1;
-
- while (minIndex <= maxIndex) {
- int midIndex = (minIndex + maxIndex) / 2;
-
-
- if (num > nums[midIndex]) {
- minIndex = midIndex + 1;
- } else if (num < nums[midIndex]) {
- maxIndex = midIndex - 1;
- } else {
- return midIndex;
- }
- }
-
- return -1;
- }
-
-
-
- public static void main(String[] args) {
-
- int[] nums = { 2,4,5,6,9,11,13,15,19,20,22, 91};
-
- int find = BinarySearch.search(nums,5);
-
- if (find != -1) {
- System.out.println("找到数值于索引" + find);
- } else {
- System.out.println("找不到数值");
- }
- }
- }