Skip to content

Instantly share code, notes, and snippets.

@xynophon
Created January 13, 2015 06:38
Show Gist options
  • Select an option

  • Save xynophon/82ff33d99896881905dd to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/82ff33d99896881905dd to your computer and use it in GitHub Desktop.
/**
* Created by xynophon on 15.1.13.
*/
public class binary_search {
public int binary_search(double[] arr, double target){
int lo = 0;
int hi = arr.length;
while(lo+1 < hi){
int mid = (lo+hi)/2;
if(target < arr[mid]){
hi = mid;
}else{
lo = mid;
}
}
if(arr[lo] == target) {
return lo;
}else{
return -1;
}
}
public int binary_search_rec(double[]arr, int lo, int hi, int target){
int mid = (lo+hi)/2;
if(lo+1 < hi) {
if (arr[mid] == target) {
return mid;
} else {
if (arr[mid] > target) {
hi = mid;
} else {
lo = mid;
}
}
}else{
return -1;
}
return binary_search_rec(arr, lo, hi, target);
}
public static void main(String args[]){
binary_search bs = new binary_search();
double[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("binary search index : " + bs.binary_search(arr, 11));
System.out.println("binary search index : " + bs.binary_search_rec(arr, 0, arr.length, 6));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment