二分法搜索数组

[java]  view plain copy
  1. public class Test2T2Method {  
  2.   
  3.     /** 
  4.      * 采用二分法查找顺序排列数组里的一个数。 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         int[] array ={1,2,3,4,5,6,7,8,9};  
  8.         int n=6;  
  9.         System.out.println(twoFind(array,n));  
  10.     }  
  11.       
  12.     public static int twoFind(int[] array,int n){  
  13.         int startPos=0;//初始起点位置  
  14.         int endPos=array.length-1;//初始结束位置  
  15.         int index=(startPos+endPos)/2;//取中点  
  16.   
  17.         while(startPos<=endPos){  
  18.             if (array.length==0){return -1;}//空数组无效  
  19.             if (n==array[index]){return index;}  
  20.             if (n>array[index]){  
  21.                 //调整起点位置  
  22.                 startPos=index+1;  
  23.             }  
  24.             if (n<array[index]){  
  25.                 //调整结束位置  
  26.                 endPos=index-1;  
  27.             }  
  28.             index=(startPos+endPos)/2;  
  29.         }  
  30.         return -1;  
  31.     }  
  32. }  

 

 

之前写成这样,当查找6的时候造成死循环,差点把系统整死.

[java]  view plain copy
  1. public class Test2T2Method {  
  2.   
  3.     /** 
  4.      * 采用二分法查找顺序排列数组里的一个数。 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         int[] array ={1,2,3,4,5,6,7,8,9};  
  8.         int length=array.length;  
  9.         int times=0;  
  10.         int n=6;  
  11.         int index=length/2;  
  12.         boolean Found=false;  
  13.         while(!Found){  
  14.             if(n==array[index]){  
  15.                 Found=true ;  
  16.             }  
  17.             if(n>array[index]){  
  18.                 index=(index+length)/2;  
  19.             }  
  20.             if(n<array[index]){  
  21.                 index=index/2;  
  22.             }  
  23.             times++;  
  24.         }  
  25.         System.out.println(index);  
  26.         System.out.println("查找这个数需循环 "+times+" 次");  
  27.     }  
  28. }  

你可能感兴趣的:(二分法搜索数组)