[英]Using a selection sort on an ArrayList of Strings
我有一個程序可以計算從 txt 文件中提取的單詞的頻率,它們存儲在 ArrayList 中。 我對使用選擇排序非常不熟悉,但它是我被要求使用的排序類型。 我已經查看了多項選擇排序,但我的排序在某處有所不足。
這是我的實際排序。
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);
}
}
}
}
這是我對字符串的比較(我很確定邏輯錯誤在這里)。
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 是具有字符串變量“word”的 class。 任何提示將非常感謝:)
為什么不直接使用這個
public int compareTo(Word w) {
return this.word.compareTo(w.word);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.