Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Concepts

Authors: David M Kroenke, David J Auer

6th Edition

0132742926, 978-0132742924

More Books

Students also viewed these Databases questions