Question

plz solve Modify binary search so that it always returns the element with the smallest index...

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);

}

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey,

Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries

Note: Brother for simplicity I have provided a test case in main itself. the modified function is in bold. Just exchange your previous function with it. Please do comment brother in case of queries.

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 if(mid>0&&a[mid-1]==key) hi=mid-1;
else return mid;
  
}

return -1;

}

public static void main(String[] args) {

int[] whitelist = {1,2,7,7,7,7,7,7,7,8,9};


System.out.println(rank(7,whitelist));

}

}

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
plz solve Modify binary search so that it always returns the element with the smallest index...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list...

    USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list and use a Merge Sort to sort the object by age. Create a class called Person : name and age Create methods that add, and delete Person from the link list Create a method that sorts the persons' objects by age. package mergesort; public class MergeSortExample { private static Comparable[] aux; // auxiliary array for merges public static void sort(Comparable[] a) { aux =...

  • Write a Java application that implements the recursive Binary Search alogrithm below: Write a Java application...

    Write a Java application that implements the recursive Binary Search alogrithm below: Write a Java application that implements the recursive Binary Search alogrithm below:/** * Performs the standard binary search using two comparisons * per level. This is a driver that calls the recursive method * @return index where item is found or NOT FOUND if not found */public static <AnyType extends Comparable<? super AnyType>> int binarySearch(AnyType [] a, AnyType x) {return binarySearch(a, x, 0, a.length -1);}/** * Hidden recursive...

  • Must be written in JAVA Code Modify Fig. 19.2 to use recursive method recursiveLinear-Search to perform...

    Must be written in JAVA Code Modify Fig. 19.2 to use recursive method recursiveLinear-Search to perform a linear search of the array. The method should receive the search key and starting index as arguments. If the search key is found, return its index in the array; otherwise, return –1. Each call to the recursive method should check one index in the array. Figure 19.2 import java.security.SecureRandom; import java.util.Arrays; import java.util.Scanner; public class LinearSearchTest{ public static int linearSearch(int data[], int searchKey)...

  • hi I need to understand how the out put become -4 in first question and out...

    hi I need to understand how the out put become -4 in first question and out put 310 for the second question please can you explain to me thanks a lot 1.(ch12. Sc16. P. 820. loop) Consider the following code: import java.util.*; public class MyLoopOneSGTest{    public static void main(String[] args){      int w = 3;      System.out.println(myLoop(w));    }    public static int myLoop(int n){       int x = 1;       for (int i = 1; i < n; i++){          x = x - i;       }...

  • Java The following questions ask about tracing a binary search. To trace the binary search, list...

    Java The following questions ask about tracing a binary search. To trace the binary search, list the value of first, last, and mid for each pass through the loop or method. Use one of these methods for your trace. public static int binarySearchIterative(int[] numbers, int target) { boolean found = false; int first = 0; int last = numbers.length - 1; while (first <= last && !found) { int mid = (first + last) / 2; if (numbers[mid] == target)...

  • Consider the following recursive method for finding the maximum element in an int array: public int...

    Consider the following recursive method for finding the maximum element in an int array: public int static max(int[] a, int lo, int hi) { if (lo > hi) return a[lo]; int mid = (lo + hi) / 2; int loMax = max(a, lo, mid); int hiMax = max(a, mid+1, hi); if (loMax > hiMax) return loMax; else return hiMax; } Write down the recurrence relation for counting the number of times the comparison if (loMax > hiMax) is performed. Use...

  • import java.util.Arrays; import stdlib.*; public class CSC300Homework4 {    /**    * As a model for...

    import java.util.Arrays; import stdlib.*; public class CSC300Homework4 {    /**    * As a model for Problem 1, here are two functions to find the minimum value of an array of ints    * an iterative version and a recursive version    *    * precondition: list is not empty    /** iterative version */    public static double minValueIterative (int[] list) {        int result = list[0];        int i = 1;        while (i <...

  • Given driver method. Complete the following Linear search method where a given element num in list[...

    Given driver method. Complete the following Linear search method where a given element num in list[ ] Class search public static int search(int list[], int num) public static void main(String args[]) { int list[] = {12, 31, 4, 100,4%; int num = 10; int result = search(list, num); if(result == -1) System.out.print("Search key is not found"); else System.out.print("Search key is present at index" + result);

  • Reimpliment this bottom-up merge-sort queue code so it does not rely on the "import edu.princeton.cs.algs4.StdRandom" and...

    Reimpliment this bottom-up merge-sort queue code so it does not rely on the "import edu.princeton.cs.algs4.StdRandom" and "import edu.princeton.cs.algs4.StdOut"imports: /* import java.util.Queue; import java.util.LinkedList; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdOut; public class BottomUpMergeSort { public static void main(String[] args) { int N=Integer.parseInt(args[0]); Double [] a = new Double [N]; for(int i=0;i<N;i++) {    a[i]=StdRandom.uniform();    } StdOut.println("Unsorted"); printArr(a); Queue que=sort(a); StdOut.println("\nSorted"); BottomUpMergeSort.printQue(que); } public static Queue sort(Double[] a) {    int N=a.length;       Queue->ques=new LinkedList>();       for(int i=0;i<N;i++) {       ...

  • I'm trying to make a recursive binary search that checks whether or not the words in...

    I'm trying to make a recursive binary search that checks whether or not the words in a file are correct by comparing it to a dictionary file, but for some reason the method I'm using below is not working and is outputting all the words in the file I am checking as incorrect. (the dictionary is organized in alphabetical order however the file "oliver.txt" is not) my question is what do I have to do to make this work? public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT