3

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Which part? Storing data as numbers, sorting them once you have them in numbers, or implementing an AlphanumComparator?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.