ralphdc09

its101.md.wk.08.09.BinarySearch

Nov 15th, 2021 (edited)
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. package its101.mdwk08_09;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class BinarySearchFinal {
  6.  
  7.     //     Create function binarySearch()
  8.     public static int binarySearch(int[] array, int lowerBound, int upperBound, int key) {
  9.         if (upperBound >= lowerBound) {
  10.             //  Set midPoint
  11.             int midPoint = lowerBound + (upperBound - lowerBound) / 2;
  12.             //  If key is found, then return its index position
  13.             if (array[midPoint] == key) {
  14.                 return midPoint;
  15.             }
  16.             //  If key is smaller than midPoint, the key is in the left sub array
  17.             if (array[midPoint] > key) {
  18.                 return binarySearch(array, lowerBound, midPoint - 1, key);
  19.             }
  20.             //  If key is larger than midPoint, the key is in the right sub array
  21.             return binarySearch(array, midPoint + 1, upperBound, key);
  22.         }
  23.         //  If key is not found, then return -1
  24.         return -1;
  25.     } //    End of function binarySearch()
  26.  
  27.     public static void main(String[] args) {
  28.  
  29.         // Create new array
  30.         int[] myArray = {3, 4, 5, 6, 7, 8, 9};
  31.         //  Set upperBound
  32.         int upperBound = myArray.length - 1;
  33.  
  34.         // Print array
  35.         System.out.println(Arrays.toString(myArray));
  36.  
  37.         // Initiate element key to be search
  38.         int key = 4;
  39.         // Initiate the search result using the binarySearch() function
  40.         int result = binarySearch(myArray, 0, upperBound, key);
  41.  
  42.         // If-else statement for printing the result
  43.         if (result != -1) {
  44.             System.out.println("Element " + key + " is present at index " + result);
  45.         } else {
  46.             System.out.println("Element " + key + " is not present in the array");
  47.         }
  48.     }
  49. }
  50.  
Add Comment
Please, Sign In to add comment