Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. public static int findFirstInSortedArrary(int[] A, int q) {
  2.         int lo = 0, hi = A.length - 1, mid = lo+(hi-lo)/2, res = -1; /*same initializations as findInSortedArrary, but with the addition of  
  3.         res = -1, such that if no element is found -1 is already stored in the variable*/
  4.         while (lo <= hi) { //the control structure does not differ from findInSortedArrary
  5.             mid = lo + (hi-lo)/2; //Crucial part of the algorithm: This formula finds the middle element of the "subarray" as lo and hi are constantly updated
  6.             if (A[mid] == q) { //Condition: middle element equals the requested element q
  7.                 res = mid; //essential difference from findInSortedArrary: the occurrence is stored and not returned immediately
  8.                 hi = mid - 1; //Since we assume the array is sorted, we have to move to the left to find the first occurrence!
  9.             }if (A[mid] < q) //Condition: current middle element is samller than the requested element
  10.                 lo = mid + 1; //Thus move to the "right" by setting the low bound to the middle element of the subarray +1
  11.             else
  12.                 hi = mid - 1; //Triggered if A[mid] < q. Thus move to the "right"
  13.             System.out.println(lo+";"+hi);
  14.         } return res; //We return the result and not -1 becaus we have to wait until the first occurrence is found (or not)!
  15.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement