Recursive solution:
public static int binarySearch(int[] array, int startIndex, int endIndex, int value){
int midIndex = (startIndex + endIndex)/2;
if(array[midIndex] == value){
return value;
}
if(startIndex > endIndex){
return -1;
}
if(value < array[midIndex]){
int sI = startIndex;
int eI = midIndex - 1;
return binarySearch(array, sI, eI, value);
}else{
int sI = midIndex + 1;
int eI = endIndex;
return binarySearch(array, sI, eI, value);
}
}
Non-Recursive solution:
public static int binarySearchNoRecursion(int[] array, int value){
int startIndex = 0;
int endIndex = array.length - 1;
while(startIndex <= endIndex){
int midIndex = (startIndex + endIndex)/2;
if(array[midIndex] == value){
return value;
}
if(value < array[midIndex]){
endIndex = midIndex - 1;
}else{
startIndex = midIndex + 1;
}
}
return -1;
}
Comments
Post a Comment