Test
We will now test all the methods and print the output.
public static void main(String[] args) {
int[] sortedArray = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int key = 12;
System.out.println("Element " + key + " is present at index: " + binarySearchIterative(sortedArray, key));
System.out.println("Element " + key + " is present at index: " + binarySearchRecursive(sortedArray, key, 0, sortedArray.length - 1));
System.out.println("Element " + key + " is present at index: " + Arrays.binarySearch(sortedArray, key));
ArrayList<Integer> sortedList = new ArrayList<Integer>(Arrays.asList(2, 4, 6, 8, 10, 12, 14, 16, 18, 20));
System.out.println("Element " + key + " is present at index: " + Collections.binarySearch(sortedList, key));
}
To run the code, we first compile the java program.
javac BinarySearch.java
Then we can run the program.
java BinarySearch