0

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 :)

5
  • What is going wrong with this? i.e. what is the incorrect behaviour? Have you tried stepping through your code in a debugger? Commented May 2, 2011 at 0:44
  • above, add, a, advanced, ago, all, as, altogether, and, any, are, be. This is a sample of how it is currently turning out. The document has about 138 unique words in it. Commented May 2, 2011 at 0:48
  • I don't think you want to implement the sort on your own. I also believe that the Word.compareTo can simply delegate to the Word's String.compareTo. Commented May 2, 2011 at 0:49
  • If you are suspicious that your compareTo method is broken, why not try testing it in isolation? Commented May 2, 2011 at 0:50
  • @ditkin That is why I am having a hard time finding useful information from Google, but I am explicitly told to manually use the selection sort. Commented May 2, 2011 at 0:51

1 Answer 1

2

Why not just use this

public int compareTo(Word w) {
    return this.word.compareTo(w.word);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually after changing the compareTo AND my sort to if (wordArray.get(i).compareTo(wordArray.get(j)) >=1) It works :) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.