Question

When binary searching a sorted array that contains more than one key equal to the search key, the client may want to know the index of either the first or the last such key. Accordingly, implement the following API: public class BinarySearchDeluxe { /* Returns the index of the first key in a[] that equals the search key, or -1 if no such key. */ public static int firstIndexOf(Key[] a, Key key, Comparator comparator) /* Returns the index of the last key in a[] that equals the search key, or -1 if no such key. */ public static int lastIndexOf(Key[] a, Key key, Comparator comparator) } Corner cases. Each static method should throw a java.lang.NullPointerException if any of its arguments is null. You should assume that the argument array is in sorted order (with respect to the supplied comparator). Performance requirements. The firstIndexOf() and lastIndexOf() methods should make at most 1 + ⌈log2 N⌉ compares in the worst case, where N is the length of the array. In this context, a compare is one call to comparator.compare().When binary searching a sorted array that contains more than one key equal to the search key, the client may want to know the

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

Working code implemented in Java and comments for better understanding:

Note: Below is the code for BinarySearchDeluxe.java . Here I have provided implementation for both firstIndexOf() and lastIndexOf(). It works fine for me. Just include the needed libraries it will work perfectly.

Code for BinarySearchDeluxe.java

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdIn;
import java.util.Arrays;
import java.util.Comparator;

// Implements binary search for clients that may want to know the index of
// either the first or last key in a (sorted) collection of keys.
public class BinarySearchDeluxe {
// The index of the first key in a[] that equals the search key,
// or -1 if no such key.
public static <Key> int firstIndexOf(Key[] a, Key key,
Comparator<Key> comparator) {
   if (a == null || key == null || comparator == null) {
       throw new java.lang.NullPointerException();
   }
   if (a.length == 0) {
       return -1;
   }
   int l = 0;
   int r = a.length - 1;
   int index = -1;
   while (l <= r) {
       int mid = l + (r - l)/2;
       if (comparator.compare(key, a[mid]) < 0) {
           r = mid - 1;
          
       } else if (comparator.compare(key, a[mid]) > 0) {
           l = mid + 1;
       } else {
       index = mid;
       r = mid - 1;
       }
   }
  
   return index;
  
}

// The index of the last key in a[] that equals the search key,
// or -1 if no such key.
public static <Key> int lastIndexOf(Key[] a, Key key,
Comparator<Key> comparator) {
   if (a == null || key == null || comparator == null) {
       throw new java.lang.NullPointerException();
   }
   if (a == null || a.length == 0) {
       return -1;
   }
   int l = 0;
   int r = a.length - 1;
   int index = -1;
   while (l <= r) {
       int mid = l + (r - l)/2;
       if (comparator.compare(key, a[mid]) < 0) {
           r = mid - 1;
       } else if (comparator.compare(key, a[mid]) > 0){
           l = mid + 1;
       } else {
       index = mid;
       l = mid + 1;
      
   }
  
  
}
return index;
}
  

// Test client. [DO NOT EDIT]
public static void main(String[] args) {
String filename = args[0];
String prefix = args[1];
In in = new In(filename);
int N = in.readInt();
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.readLong();
in.readChar();
String query = in.readLine();
terms[i] = new Term(query.trim(), weight);
}
Arrays.sort(terms);
Term term = new Term(prefix);
Comparator<Term> prefixOrder = Term.byPrefixOrder(prefix.length());
int i = BinarySearchDeluxe.firstIndexOf(terms, term, prefixOrder);
int j = BinarySearchDeluxe.lastIndexOf(terms, term, prefixOrder);
int count = i == -1 && j == -1 ? 0 : j - i + 1;
StdOut.println(count);
}
}

Code Screenshots:

import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.Stdout; import edu.princeton.cs.algs4.StdIn; import java.util1 = mid + 1; return index; 68 } // Test client. [DO NOT EDIT] public static void main(String[] args) { String filename = args

Hope it helps. Thank you.

Add a comment
Know the answer?
Add Answer to:
When binary searching a sorted array that contains more than one key equal to the search...
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
  • QUESTION 12 If an array contains unordered values, searching for a particular value O is accomplished...

    QUESTION 12 If an array contains unordered values, searching for a particular value O is accomplished with a linear search is accomplished with the bipolar search O can't be done in Java O requires multiple parallel processing threads QUESTION 13 What best describes the processing of the following method? public static t[] mystery (int[] list) int[] result = new int[list.length]; j 1; for (int i = 0, result.length i < list.length; i++, j--) { result[j] = list[i]; } return result;...

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

  • 6 (10 points Remember the recursive Searching algorithm Binary Search. Write a recursive method to search...

    6 (10 points Remember the recursive Searching algorithm Binary Search. Write a recursive method to search for a target character in the array and return the index location if found or -1 if it is not found. 7 a5 points 17 points cach) Write the code to create a GUI based class Temperature Converter which inherits from JFrame and implements the ActionListerner interface. public static int binary Search(char target, char( theValues, int firstIndex, int lastindex) Example: Clicked "F to C"...

  • JAVA Objectives: 1. Apply linear search algorithm 2. Apply select sort algorithm 3. Apply array iteration...

    JAVA Objectives: 1. Apply linear search algorithm 2. Apply select sort algorithm 3. Apply array iteration skill Problem description: Write the following eight methods and write a main function to test these methods // return the index of the first occurrence of key in arr // if key is not found in arra, return -1 public static int linearSearch(int arr[], int key) // sort the arr from least to largest by using select sort algorithm public stati void selectSort(int arr[])...

  • Question 3 Searching Algorithms [12 marks (4 marks) Define a method that when passed an array...

    Question 3 Searching Algorithms [12 marks (4 marks) Define a method that when passed an array of integers arr and another integer target, returns the last index in arr where target exists and -1 if target isn't found in arr a. b. (4 marks) Provide a trace, in the form of a logic table, of running the following method for 1, 4, 4, 4, 5, 7, 8, 12, 12, 15, 16, 17, 35, 35, 35, 40 arr = target 14...

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

  • C++ Time the sequential search and the binary search methods several times each for randomly generated...

    C++ Time the sequential search and the binary search methods several times each for randomly generated values, then record the results in a table. Do not time individual searches, but groups of them. For example, time 100 searches together or 1,000 searches together. Compare the running times of these two search methods that are obtained during the experiment. Regarding the efficiency of both search methods, what conclusion can be reached from this experiment? Both the table and your conclusions should...

  • 1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array...

    1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array of distinct integers, and an integer x, return the index of x in the array. If the element x is not present in the array, return -1. "Almost sorted" means the following. Assume you had a sorted array A[0…N], and then split it into two pieces A[0…M] and A[M+1…N], and move the second piece upfront to get the following: A[M+1]…A[N]A[0]…A[M]. Thus, the "almost sorted"...

  • java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait)...

    java Create the following classes: DatabaseType: an interface that contains one method 1. Comparator getComparatorByTrait(String trait) where Comparator is an interface in java.util. Database: a class that limits the types it can store to DatabaseTypes. The database will store the data in nodes, just like a linked list. The database will also let the user create an index for the database. An index is a sorted array (or in our case, a sorted ArrayList) of the data so that searches...

  • //Generic interface that describes various searching and sorting //algorithms. Note that the type parameter is unbounded....

    //Generic interface that describes various searching and sorting //algorithms. Note that the type parameter is unbounded. However, //for these algorithms to work correctly, the data objects must //be compared using the method compareTo and equals. //In other words, the classes implementing the list objects //must implement the interface Comparable. The type parameter T //is unbounded because we would like to use these algorithms to //work on an array of objects as well as on objects of the classes //UnorderedArrayList and...

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