Note that there are some explanatory texts on larger screens.

plurals
  1. POimplement binary search with string prefix?
    primarykey
    data
    text
    <p>How can I implement binary search to find a string with a particular prefix in generic array (which in this case will be a string[]). I tried compareTo but that wouldn't help because i have to use a string prefix. eg String prefix "Bi" bill, bilards ...etc..</p> <p>Implement the following method to return all strings in an alphabetically sorted array that start with a given prefix. For instance, given a prefix “bi”, the returned strings are ”Bill Clinton”, ”Bill Gates”, and ”Bill Joy”. Note that all string comparisons should be case INSENSITIVE. The strings in the returned list must be in the order in which they appear in the array. Your implementation must be based on binary search, and must run in worst case O(log n+k) time, where n is the length of the array, and k is the number of matching strings. Assume that the array has no duplicate entries. If there are no matches, you may either return null, or an empty array list.</p> <p>You may use the following String methods (in addition to any others you may recall): boolean startsWith(String s) int compareTo(String s) int compareToIgnoreCase(String s) String toLowerCase(String s) String toUpperCase(String s) (As for ArrayList, you only need to use the add method to add an item to the end of the array list.) You may write helper methods (with full implementation) as necessary. You may not call any method that you have not implemented yourself</p> <pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; ArrayList prefixMatch(T[] list, String prefix) { ArrayList&lt;T&gt; result = new ArrayList&lt;T&gt;(); int lo = 0; int hi = list.length - 1; while(lo &lt;= hi) { int mid = (hi + lo) / 2; list[mid].startsWith(prefix) ? 0 : list[mid].compareTo((T) prefix)); } return null; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload