二分法搜索数组

64 篇文章 1 订阅

[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. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值