Java Reference
In-Depth Information
int numWords = 0;
String word = getWord(in).toLowerCase();
while (!word.equals("")) {
int loc = binarySearch(word, wordList, 0, numWords-1);
if (word.compareTo(wordList[loc]) == 0) ++frequency[loc]; //word found
else //this is a new word
if (numWords < MaxWords) { //if table is not full
addToList(word, wordList, frequency, loc, numWords-1);
++numWords;
}
else out.printf("'%s' not added to table\n", word);
word = getWord(in).toLowerCase();
}
printResults(out, wordList, frequency, numWords);
in.close();
out.close();
} // end main
public static int binarySearch(String key, String[] list, int lo, int hi){
//search for key from list[lo] to list[hi]
//if found, return its location;
//if not found, return the location in which it should be inserted
//the calling program will check the location to determine if found
while (lo <= hi) {
int mid = (lo + hi) / 2;
int cmp = key.compareTo(list[mid]);
if (cmp == 0) return mid; // search succeeds
if (cmp < 0) hi = mid -1; // key is 'less than' list[mid]
else lo = mid + 1; // key is 'greater than' list[mid]
}
return lo; //key must be inserted in location lo
} //end binarySearch
public static void addToList(String item, String[] list, int[] freq, int p, int n) {
//adds item in position list[p]; sets freq[p] to 1
//shifts list[n] down to list[p] to the right
for (int h = n; h >= p; h--) {
list[h + 1] = list[h];
freq[h + 1] = freq[h];
}
list[p] = item;
freq[p] = 1;
} //end addToList
public static void printResults(PrintWriter out, String[] list, int freq[], int n) {
out.printf("\nWords Frequency\n\n");
for (int h = 0; h < n; h++)
out.printf("%-20s %2d\n", list[h], freq[h]);
} //end printResults
Search WWH ::




Custom Search