Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int findFirstInSortedArrary(int[] A, int q) {
- int lo = 0, hi = A.length - 1, mid = lo+(hi-lo)/2, res = -1; /*same initializations as findInSortedArrary, but with the addition of
- res = -1, such that if no element is found -1 is already stored in the variable*/
- while (lo <= hi) { //the control structure does not differ from findInSortedArrary
- 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
- if (A[mid] == q) { //Condition: middle element equals the requested element q
- res = mid; //essential difference from findInSortedArrary: the occurrence is stored and not returned immediately
- hi = mid - 1; //Since we assume the array is sorted, we have to move to the left to find the first occurrence!
- }if (A[mid] < q) //Condition: current middle element is samller than the requested element
- lo = mid + 1; //Thus move to the "right" by setting the low bound to the middle element of the subarray +1
- else
- hi = mid - 1; //Triggered if A[mid] < q. Thus move to the "right"
- System.out.println(lo+";"+hi);
- } return res; //We return the result and not -1 becaus we have to wait until the first occurrence is found (or not)!
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement