john
john

Reputation: 313

Creating an algorithm that can sort string/integer arrays

I am trying to figure out how to make a sorting function that will sort an array in descending order.

public void dsort(String field) throws DataSetException {
    int front = 0;
    int findex = -1;

    String[] tosort = new String[50];
    for (int i = 0; i < filedata[0].length; i++) {
        if (field.equalsIgnoreCase(filedata[0][i])) {
            findex = i;
        }
    }
    if (findex == -1) {
        throw new DataSetException();
    } else {
        for (int k = 0; k < getNumRecords(); k++) {
            if (filedata[k][findex] != null) {
                tosort[front] = filedata[k][findex];
                front++;
            }
        }
        Comparator comparator = Collections.reverseOrder();
        Arrays.sort(tosort, comparator);
        System.out.println(Arrays.asList(tosort));
    }
}

What this does is creates a new array by taking elements from an array of arrays, which is what I want it to do. However, the output of my sort is something like 32, 3, 25, 20, 2, 1000, 1 etc.. These "integers" are considered strings, and this sorting function is supposed to also be able to sort words as strings. I think I should be trying to use comparable, but I am unsure of how to implement it in this situation.

Upvotes: 3

Views: 659

Answers (2)

sjr
sjr

Reputation: 9875

Using Google Guava:

List<String> sortedList = Ordering.natural().reverse().onResultOf(new Function<String, Integer>() {
  @Override public Integer apply(String input) {
    return Integer.valueOf(input); // assumes input is always valid
  }
}).immutableSortedCopy(Iterables.concat(listOfLists));

Or something like that. The Iterables.concat will take an iterable of iterables and turn it into a single iterable for you. You will probably need to turn your array of arrays into a List of Lists.

Upvotes: 0

JohnnyO
JohnnyO

Reputation: 3068

If everything really is a number, then you don't want to store them as String, store them as numbers and then use a numeric sort.

If on the other hand, you have a combination of Strings, some of which are numeric, and some of which are alphabetic, I'd recommend using something like an AlphanumComparator, available here

Upvotes: 2

Related Questions