少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
//递归性
package com.abin.lee.algorithm.binary;
public class BinarySearch {
public static void main(String[] args) {
int[] input = new int[]{2,3,4,5,6,7,8,9}; 
int result = search(input, 5, 0, input.length-1);
System.out.println("result="+result);
}
public static int search(int[] input,int data,int low,int high){
int middle = (low+high)/2;
if(data == input[middle]){
return middle;
}else if(data > input[middle]){
return search(input, data, middle+1, high);
}else if(data < input[middle]){
return search(input, data, low, middle-1);
}else{
return -1;
}
}
}


//while循环型
public static int binary(int[] input,int low,int high,int target){
while(low <= high){
int middle = (low+high)/2;
if(input[middle]>target){
high = middle-1;
}else if(input[middle]<target){
low = middle+1;
}else{
return middle;
}
}
return -1;
}
posted on 2014-10-11 00:03 abin 阅读(338) 评论(0)  编辑  收藏 所属分类: algorithm

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


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问