Wednesday, March 16, 2011

WAP to Sort Most Freq..Appearing Word Based on Their Frequency From Non Incresing Order

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class WordCounting
{
static final Integer ONE = new Integer(1);

public static void main(String args[]) throws IOException {
Hashtable map = new Hashtable();
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
String line;
StringTokenizer st;
while ((line = br.readLine()) != null)
{

st= new StringTokenizer(line," ");

while (st.hasMoreTokens())
{
String word=st.nextToken();
Object obj = map.get(word);

if (obj == null)
{
map.put(word, ONE);
}
else
{
int i = ((Integer) obj).intValue() + 1;
map.put(word, new Integer(i));
}
//word=null;
}

}

Enumeration e = map.keys();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
System.out.println(key + " : " + map.get(key));
}


//sort According to Freqency of valuew of each word

Collection set = map.values();
Iterator iter = set.iterator();
Integer ar[]=new Integer[map.size()];
int i=0;
while (iter.hasNext())
{
ar[i]=(Integer)iter.next();

i++;
}


quickSort(ar,0,i);

for(i=0;i System.out.println(ar[i]);


//After Sorting Printing According to Freq from Higer to Lower


/* Enumeration e = map.keys();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
System.out.println(key + " : " + map.get(key));
}*/






}


private static void quickSort(Integer arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}

private static int partition(Integer arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}




}

No comments :