随笔-14  评论-142  文章-0  trackbacks-0
public  int find(int[] values, int key){
        
        
        
        
int lowerBound = 0;
        
        
        
int upperBound = values.length -1 ;
        
        
int curIn;
        
        
while(true){
            
            curIn 
= (lowerBound + upperBound ) / 2;
            
            
if(values[curIn] == key){
                
return curIn;
                
            }
else if(lowerBound > upperBound){
                
                
                
                
return values.length;
                
            }

            
            
            
else{
                
if(values[curIn] < key){
                    
                    
                    
                    lowerBound 
= curIn + 1;
                    
                }
else{
                    upperBound 
= curIn - 1;
                    
                }

            }

            
            
            
        }

        
        
        
        
    }
posted on 2007-09-06 18:02 liulang 阅读(5202) 评论(4)  编辑  收藏

评论:
# re: java折半查找算法 2009-02-18 20:56 | 天涯浪子
你这个代码有错吧 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄  回复  更多评论
  
# re: java折半查找算法 2009-02-18 21:02 | 天涯浪子
int[] ints = { 34, 13, 53, 64, 58, 21, 60, 78, 651, 564, 55 };
System.out.println(find(ints, 64));
调用结果还是11。。。。靠,受不了了...  回复  更多评论
  
# re: java折半查找算法 2009-06-11 11:38 | 紫宸
拜托 搞的代码要能跑出结果才行啊!  回复  更多评论
  
# re: java折半查找算法 2009-08-17 13:52 | Jose
看你们的回复...我崩溃了..
折半查找是要求在一个有序的数列当中查找
你给人家一个无序数怎么查找???

int[] ints = { 2, 23, 53, 64, 158, 221, 260, 278, 651, 1564, 2355 };
System.out.println(find(ints, 651));

这个总可以吧?  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: