java数组实现二分法查找算法

二分法查找的关键是根据数组中间索引进行不断的二分来实现对数据的查找,注意此处数组必须为有序数组,示例代码如下:

  1. public class BinarySearch {  
  2.     /** 
  3.      在二分法查找中,从数列的中间开始搜寻,如果这个数小于我们所搜寻的数,由于数列已排序,则该数左边的数一定都小于要搜寻的对象,所以无需浪费时间在左边的数;如果搜寻的数大于所搜寻的对象,则右边的数无需再搜寻,直接搜寻左边的数。 
  4.   
  5.      */  
  6.     public static int search(int[] nums, int num) {  
  7.         int minIndex = 0;  
  8.         int maxInde = nums.length - 1;  
  9.   
  10.         while (minIndex <= maxIndex) {  
  11.             int midIndex = (minIndex + maxIndex) / 2;  
  12.               
  13.             //与中间值比较确定在左边还是右边区间,以调整区域  
  14.             if (num > nums[midIndex]) {  
  15.                 minIndex = midIndex + 1;  
  16.             } else if (num < nums[midIndex]) {  
  17.                 maxIndex = midIndex - 1;  
  18.             } else {  
  19.                 return midIndex;  
  20.             }  
  21.         }  
  22.   
  23.         return -1;  
  24.     }  
  25.       
  26.       
  27.     //二分查找的实现  
  28.     public static void main(String[] args) {  
  29.   
  30.         int[] nums = { 2,4,5,6,9,11,13,15,19,20,22, 91};  
  31.       
  32.         int find = BinarySearch.search(nums,5);  
  33.           
  34.         if (find != -1) {  
  35.             System.out.println("找到数值于索引" + find);  
  36.         } else {  
  37.             System.out.println("找不到数值");   
  38.         }  
  39.     }  
  40. }  

猜你喜欢

转载自blog.csdn.net/pmt1982/article/details/55058008