Search code examples
javastringsortingpriority-queuecpu-word

Using Priority Queue with Custom Comparator to Sort Based on Number of Words in a String?


I'm trying to use Priority Queue to sort strings based on how many words (white spaces) there are in each string. My code works only in certain scenerios, but not when the amount of white spaces per string is really spread out. I think because my methods aren't comparing them all.

Comparator<String> whiteSpaces = new Comparator<String>() {
        int count1 = 0;
        int count2 = 0;
        char c = ' ';
        @Override
        public int compare(String s1, String s2) {
            for(int i = 0; i < s1.length(); i++) {
                if(s1.charAt(i) == c){
                    count1++;
                }
            }
            for(int i = 0; i < s2.length(); i++) {
                if(s2.charAt(i) == c) {
                    count2++;
                }
            }
            return count1 - count2;
        }
    };

Could I modify what I have so that it compares to all the strings added to the priorityqueue? Thanks in advance.


Solution

  • The Comparator isn't working because you don't reset count1 and count2 to 0 between calls to compare().

    Actually, the problem is that count1 and count2 are fields. They should be local variables.

    Move count1 and count2 declarations into the method.

    Comparator<String> whiteSpaces = new Comparator<String>() {
        char c = ' ';
        @Override
        public int compare(String s1, String s2) {
            int count1 = 0;
            int count2 = 0;
            for(int i = 0; i < s1.length(); i++) {
                if(s1.charAt(i) == c){
                    count1++;
                }
            }
            for(int i = 0; i < s2.length(); i++) {
                if(s2.charAt(i) == c) {
                    count2++;
                }
            }
            return count1 - count2;
        }
    };
    

    Other improvements:

    • Field c should be private and final, and better named.

    • Create a helper method to eliminate repeated code.

    • Use Integer.compare(a, b) instead of subtraction.

    Comparator<String> whiteSpaces = new Comparator<String>() {
        private final char separator = ' ';
        @Override
        public int compare(String s1, String s2) {
            return Integer.compare(countSeparators(s1), countSeparators(s2));
        }
        private int countSeparators(String s) {
            int count = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == separator) {
                    count++;
                }
            }
            return count;
        }
    };