Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package its101.mdwk08_09;
- import java.util.Arrays;
- public class BinarySearchFinal {
- // Create function binarySearch()
- public static int binarySearch(int[] array, int lowerBound, int upperBound, int key) {
- if (upperBound >= lowerBound) {
- // Set midPoint
- int midPoint = lowerBound + (upperBound - lowerBound) / 2;
- // If key is found, then return its index position
- if (array[midPoint] == key) {
- return midPoint;
- }
- // If key is smaller than midPoint, the key is in the left sub array
- if (array[midPoint] > key) {
- return binarySearch(array, lowerBound, midPoint - 1, key);
- }
- // If key is larger than midPoint, the key is in the right sub array
- return binarySearch(array, midPoint + 1, upperBound, key);
- }
- // If key is not found, then return -1
- return -1;
- } // End of function binarySearch()
- public static void main(String[] args) {
- // Create new array
- int[] myArray = {3, 4, 5, 6, 7, 8, 9};
- // Set upperBound
- int upperBound = myArray.length - 1;
- // Print array
- System.out.println(Arrays.toString(myArray));
- // Initiate element key to be search
- int key = 4;
- // Initiate the search result using the binarySearch() function
- int result = binarySearch(myArray, 0, upperBound, key);
- // If-else statement for printing the result
- if (result != -1) {
- System.out.println("Element " + key + " is present at index " + result);
- } else {
- System.out.println("Element " + key + " is not present in the array");
- }
- }
- }
Add Comment
Please, Sign In to add comment