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 =...

  • 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)...

  • 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...

  • Need help with this Java project implementing an interpolation search, bolded the missing parts: /**   ...

    Need help with this Java project implementing an interpolation search, bolded the missing parts: /**    A class that implements an interpolation search and    a binary search of a sorted array of integers.    @author Frank M. Carrano    @author Timothy M. Henry    @version 4.0 */ public class SearchComparer {    private int[] a;    private int interpolationSearchCounter;    private int binarySearchCounter;    private static final int CAPACITY = 50;    public SearchComparer(int[] array, int n)    {...

  • package homework; import java.util.Arrays; import stdlib.*; /** CSC300Homework4 version 1.0 * *    * * Find...

    package homework; import java.util.Arrays; import stdlib.*; /** CSC300Homework4 version 1.0 * *    * * Find the 3 Sections marked TODO: * * TODO #1: SumOddsRecursive * TODO #2: ReverseArray * TODO #3: MergeArrays * * You must not add static variables. You MAY add static functions. * * It is okay to add functions, such as * * <pre> * public static double sumOfOddsHelper (double[] list, int i) { * </pre> * * but it is NOT okay to...

  • 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...

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

  • Teacher Instructions: Create the binarySearch() method for String arrays from the downloaded version for ints so...

    Teacher Instructions: Create the binarySearch() method for String arrays from the downloaded version for ints so the program can find String. Wrap a main around it, of course, so that we can see how it works. Provided Code: // Returns the index of an occurrence of target in a, // or a negative number if the target is not found. // Precondition: elements of a are in sorted order public static int binarySearch(int[] a, int target) { int min =...

  • COMPLETE BigMerge public class BigMerge {       /*    * Returns j such that a[j][index[j]]...

    COMPLETE BigMerge public class BigMerge {       /*    * Returns j such that a[j][index[j]] is the minimum    * of the set S={a[i][index[i]] for every i such that index[i]<a[i].length}    * If the set S is empty, returns -1    * Runs in time a.length.    *    * NOTE: normally this would be private, but leave it    * public so we can test it separately from your merge.    */    public static int argMin(int [][]...

  • Write merge method for mergeSort method, it takes the array of data, starting index of first...

    Write merge method for mergeSort method, it takes the array of data, starting index of first half, starting index of second half and end index of second half. please use the code below to test it public class A4Sort{ public static void mergeSort(int[] a, int l, int h){ if (l >= h) return; int mid = (h + l) / 2; mergeSort(a, l, mid); mergeSort(a, mid + 1, h); merge(a, l, mid + 1, h); } public static void main(String[]...

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
ADVERTISEMENT