Created
August 14, 2016 15:33
-
-
Save sbsatter/9295f02692da2085dfbeb6ff55f7d21d to your computer and use it in GitHub Desktop.
Recursively search for a given element in an array using binary search. The element to find is passed as the last argument and the array is the preceding series of arguments from command prompt!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
class RecursiveBinarySearch{ | |
static int elem; | |
static int passNumber=1; | |
public static void main(String ... args){ | |
elem=Integer.parseInt(args[args.length-1]); | |
int [] array; | |
if(args.length!=0){ | |
array= new int [args.length-1]; | |
for(int i=0; i<args.length-1; i++){ | |
array[i]=Integer.parseInt(args[i]); | |
} | |
Arrays.sort(array); | |
System.out.println(binarySearch(array, 0, array.length-1)); | |
} | |
} | |
public static int binarySearch(int [] array, int first, int last){ | |
System.out.print("Pass "+(passNumber++)+": "); | |
for(int i= first; i<=last; i++){ | |
System.out.print(array[i]+" "); | |
} | |
System.out.println(); | |
int middle= (first+last)/2; | |
if(elem>array[middle]){ | |
//check right part of array | |
return binarySearch(array, middle+1, last); | |
}else if(elem<array[middle]){ | |
//check left part of array | |
return binarySearch(array, first, middle-1); | |
}else if(elem == array[middle]){ | |
//elem is middle element | |
return middle; | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment