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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With