简体   繁体   English

对字符串的 ArrayList 使用选择排序

[英]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.我有一个程序可以计算从 txt 文件中提取的单词的频率,它们存储在 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". Word 是具有字符串变量“word”的 class。 Any tips would be greatly appreciated:)任何提示将非常感谢:)

Why not just use this为什么不直接使用这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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