I know this is a very famous question and lots of answers provided already, but I am trying to implement binary search algorithm in java of my own.
First of all getting following compilation error, why??
This method must return a result of type int
Second how this approach differs from this famous solution
public static int binarySearch(int test[], int num){
int midLength = test.length/2;
int fullLength = test.length;
if(num > test[midLength]){
int newArray[] = new int[fullLength - midLength];
for (int j = 0; j<= midLength ; j++){
newArray[j] = test[midLength + j];
}
return binarySearch(newArray, num);
}
else if(num < test[midLength]){
int newArray[] = new int[midLength];
for (int j = 0; j<= fullLength - midLength ; j++){
newArray[j] = test[j];
}
return binarySearch(newArray, num);
}
else if(num == test[midLength]){
return test[midLength];
}
}
public static void main(String[] args) {
int test[] = {2,8,1,6,4,6};
Arrays.sort(test);
int num = ArraysTest.binarySearch(test, 1);
System.out.println(num);
}
Please ignore the boundary conditions and logical mistakes, as this is draft version.