Be alaways javaing...

Loving Java
posts - 43, comments - 5, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

二分搜索法

Posted on 2008-10-10 16:19 追风舞者 阅读(197) 评论(0)  编辑  收藏 所属分类: 数据结构与算法
public class Search {

    
/**
     * 前提条件array数组已排序
     
*/
    
public static boolean binarySearch(int[] array, int target) {
        
boolean result = false;
        
int bottom = 0;
        
int top = array.length-1;
        
while (bottom <= top) {
            
int mid = (top + bottom) / 2;
            
if (target == array[mid]) {
                result 
= true;
                
break;
            } 
else if (target < array[mid]) {
                top 
= mid - 1;
            } 
else if (target > array[mid]) {
                bottom 
= mid + 1;
            }
        }

        
return result;
    }

    
public static void main(String[] args) {
        
int [] array = {1,3,5,7,9,10};
        
boolean result = binarySearch(array, 10);
        System.out.println(result);
    }
}

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


网站导航: