Question: plz solve Modify binary search so that it always returns the element with the smallest index * that matches the search element (and still guarantees

plz solve Modify binary search so that it always returns the element with the smallest index * that matches the search element (and still guarantees logarithmic running time).

import java.util.Arrays;

public class BinarySearch2 { public static int rank(int key, int[] a) { // Array must be sorted.

int lo = 0; int hi = a.length - 1;

while (lo <= hi) { // Key is in a[lo..hi] or not present.

int mid = lo + (hi - lo) / 2;

if (key < a[mid]) hi = mid - 1;

else if (key > a[mid]) lo = mid + 1;

else return mid; }

return -1;

}

public static void main(String[] args) {

int[] whitelist = In.readInts(args[0]);

Arrays.sort(whitelist);

while (!StdIn.isEmpty()) { // Read key, print if not in whitelist

int key = StdIn.readInt();

if (rank(key, whitelist) < 0)

StdOut.println(key);

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!