In "Programming Pearls" I have met the following problem. The question is this: "print words in order of decreasing frequency". As I understand problem is this. Suppose there is a given string array, let's call it s
(words I have chosen randomly, it does not matter),
String s[]={"cat","cat","dog","fox","cat","fox","dog","cat","fox"};
We see that string "cat" occurs 4 times, "fox" 3 times and "dog" 2 times. So the desired result will be this:
cat
fox
dog
I have written the following code in Java:
import java.util.*;
public class string {
public static void main(String[] args){
String s[]={"fox","cat","cat","fox","dog","cat","fox","dog","cat"};
Arrays.sort(s);
int counts;
int count[]=new int[s.length];
for (int i=0;i<s.length-1;i++){
counts=1;
while (s[i].equals(s[i+1])){
counts++;
}
count[i]=counts;
}
}
}
I have sorted the array and created a count array where I write the number of occurrences of each word in array.
My problem is that somehow the index of the integer array element and the string array element is not the same. How can I print words according to the maximum elements of the integer array?