简体   繁体   中英

Using a selection sort on an ArrayList of Strings

I have a program that is counting the frequencies of words taken from a txt file and they are being stored in an ArrayList. I am extremely unfamiliar with using a selection sort but it is the type of sort that I am being asked to use. I have looked at multiple selection sorts, but mine is falling short somewhere along the line.

This is my actual sort.

private void sort() {

    for (int i = 0; i < wordArray.size() - 1; i++) {
        for (int j = i + 1; j < wordArray.size(); j++) {
            if (wordArray.get(i).compareTo(wordArray.get(j)) == 1) {

                Word temp = wordArray.get(i);
                wordArray.set(i, wordArray.get(j));
                wordArray.set(j, temp);
            }
        }
    }
}

This is my comparison of strings (I am pretty sure the logic error is in here).

public int compareTo(Word w) {

    for (int i = 0; i < this.word.length() - 1; i++) {
        if (i <= w.word.length() - 1) {
            if (this.word.charAt(i) < w.word.charAt(i)) {
                return -1;
            } else if (this.word.charAt(i) > w.word.charAt(i)){
                return 1;
            }
        }
    }
    return -1;
}

Word is a class that has the String variable "word". Any tips would be greatly appreciated:)

Why not just use this

public int compareTo(Word w) {
    return this.word.compareTo(w.word);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM