开发者

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开发者_如何学Go 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜