4

I'm trying to implement a CircularSuffixArray class in Java (Suffix array Wikipedia). In my approach, I created an inner class that implements Comparator to compare the first char of each suffix and, if they are equals, recursively call compare for the next characters. Something like this:

public class CircularSuffixArray {
    private String string;
    private int[]  sortSuffixes;

    private class SuffixesOrder implements Comparator<Integer> {
        public int compare(Integer i, Integer j) {
            if      ((length() - 1) < i) return 1;
            else if ((length() - 1) < j) return -1;
            if (string.charAt(i) != string.charAt(j))
                return compare(string.charAt(i), string.charAt(j));
            else
                return compare(i+1, j+1);
        }

        private int compare(char a, char b) {
            return b - a;
        }
    }   

    private Comparator<Integer> suffixesOrder() {
        return new SuffixesOrder();
    }

    // circular suffix array of s
    public CircularSuffixArray(String s) {
        if (s == null) throw new NullPointerException("null argument");
        string = s;
        sortSuffixes = new int[length()];
        for (int i = 0; i < length(); i++)
            sortSuffixes[i] = (length() - 1) - i;
        Arrays.sort(sortSuffixes, suffixesOrder());
    }
}

But when I tried to compile it, I get this error:

CircularSuffixArray.java:35: error: no suitable method found for sort(int[],Comparator<Integer>) Arrays.sort(sortSuffixes, suffixesOrder());

Call you tell me:

  1. First of all, if the implementation is ok (I now that there are a lot of code releated but I want to try by myself)
  2. Regardless the "algorithm" is wrong, can you help me to figured out why I get this error?
fferrin
  • 888
  • 2
  • 12
  • 29

1 Answers1

0

I think your approach is okay from what I can see. The reason you get the error, I believe, is that you are mixing int and Integer. Java does some unboxing (i.e. converting Integers to ints) and boxing (converting ints to Integers) automatically, but not in the case of an array.

If you look at the Arrays class (https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html), you'll find the sort method you're trying to call:

sort(T[] a, Comparator<? super T> c)

The T[] means your array must be an extendable type, which primitives are not. So you'll need to make your array of type Integer[] instead of int[].

I also don't know where length() is defined. I'm assuming you want the length of the string, so I'd add the following method:

public int length() {
    return string.length();
}
  • I suspected that... But I tried to not use Integer because it's a pointer and its size is greater than an int (the problem is from Coursera, Algorithms II, and they are very strict with optimizations). I'll try with Integer. And yes, I forgot to copy the length() method. Thanks! – fferrin May 02 '16 at 23:46