にぶんほうアルゴリズム
1511 ワード
public class TestBinarySearch {
public static void main(String[] args) {
int [] array = {1,7,9,25,64,98};
int index1 = binarySearch(9,array,0,array.length);
System.out.println("Index : "+index1);
int index2 = binarySearch2(array,9,0,array.length);
System.out.println("Index : "+index2);
}
public static int binarySearch(int elem,int array [],int low,int high){
if(low>high)return -1;
int mid = (low+high)/2;
if(array[mid] == elem)return mid;
if(array[mid] < elem) return binarySearch(elem,array,mid+1,high);
if(array[mid] > elem) return binarySearch(elem, array, low, mid-1);
return -1;
}
public static int binarySearch2(int[] data,int goal,int left,int right){
int mid = (left+right)/2 ;
if(left>right){
return -1 ;
}
if(goal==data[mid]){
return mid ;
}
else if(goal<data[mid]){
// right = mid -1 ;
return binarySearch2(data,goal,left,mid-1);
}
else if(goal>data[mid]){
return binarySearch2(data,goal,mid+1,right);
}
return -1 ;
}
}