im trying to do the autocomplete assignment for the algorithm and data structure class, in the assignment its ask you to create a class that finds the first occurance of a key, and last occurance of a key.
the problem that im running into is that i dont understand how to implement the comparator in this problem,im having problems setting up a binary search since when i try to compare key < a[mid] its says bad operand for binary operator, since im using objects, where i understand the comparator comes into effect, but how?
// Return the index of the first key in a[] that equals the search key, or -1 if no such key. uses binary search
public static <Key>int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
int low = 0;
int high = a.length - 1;
int result = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (key == a[mid]) {
result = mid;
high = mid - 1;
}else if (key < a[mid]) { //**<--- throws bad operand type for binary operator**
high = mid - 1; // key is probable to lie before mid element
}else {
low = mid +1; // key is probable to lie after mid
}
}
return result;
}
the comparator in question that im supposed to be passing goes likes this, it find the rValue using substring method in a string to see if the prefix order between two objects match. again i dont know if im even doing this right to begin with, but thats not the issue, the issue is how will i implement this in the other class
// Compare the terms in lexicographic order but using only the first r characters of each query.
public static class prefixOrder implements Comparator<Term>
{ public prefixOrder(int r){
rValue = r;
}
@Override
public int compare(Term v, Term w){
return v.queryItem.substring(rValue).compareTo(w.queryItem.substring(rValue));
}
}
link to the assignment https://www.cs.princeton.edu/courses/archive/fall14/cos226/assignments/autocomplete.html