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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started