Sorting words in order of frequency? (least to greatest)

前端 未结 4 2283
孤独总比滥情好
孤独总比滥情好 2021-01-06 07:05

does any one have any idea how to sort a list of words in the order of their frequency (least to greatest) using the built in collection.sort and a compar

4条回答
  •  执笔经年
    2021-01-06 07:44

    You can compare and extract ideas from the following:

    public class FrequencyCount {
    
        public static void main(String[] args) {
    
            // read in the words as an array
            String s = StdIn.readAll();
            // s = s.toLowerCase();
            // s = s.replaceAll("[\",!.:;?()']", "");
            String[] words = s.split("\\s+");
    
            // sort the words
            Merge.sort(words);
    
            // tabulate frequencies of each word
            Counter[] zipf = new Counter[words.length];
            int M = 0;                                        // number of distinct words
            for (int i = 0; i < words.length; i++) {
                if (i == 0 || !words[i].equals(words[i-1]))   // short-circuiting OR
                    zipf[M++] = new Counter(words[i], words.length);
                zipf[M-1].increment();
            }
    
            // sort by frequency and print
            Merge.sort(zipf, 0, M);                           // sorting a subarray
            for (int j = M-1; j >= 0; j--) {
                StdOut.println(zipf[j]);
            }
        }
    }
    

提交回复
热议问题