Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an algorithm that can sort string/integer arrays

Tags:

java

sorting

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.

like image 259
john Avatar asked Aug 17 '26 09:08

john


1 Answers

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

like image 96
JohnnyO Avatar answered Aug 18 '26 21:08

JohnnyO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!