In: Computer Science
Sort a string array by frequency
given an array of string write a function that will return an array that is sorted by frequency
example
{"hello","hola","hello","hello","ciao","hola","hola","hola"}
returned array should be
{"hola","hello","ciao"}
CODE IN JAVA:
Sort.java file:
import java.util.*;
public class Sort {
public static String[] sortByFrequency(String arr[])
{
ArrayList<String> uniqueList
= new ArrayList<String>();
for(int i=0;i<arr.length;i++)
{
if(uniqueList.indexOf(arr[i])==-1)
uniqueList.add(arr[i]);
}
int n = uniqueList.size();
int countWords[]= new int[n];
int count,i=0;
for(String word:uniqueList) {
count = 0
;
for(int
j=0;j<arr.length;j++) {
if(arr[j].equals(word))
count += 1 ;
}
countWords[i] =
count ;
i+=1;
}
String uniqueWords[] = new
String[n];
i=0;
for(String word:uniqueList) {
uniqueWords[i] =
word;
i+=1;
}
//sorting the array of strings by
frequency
for(i=0;i<n;i++) {
for(int
j=0;j<n-1;j++) {
if(countWords[j]<countWords[j+1]) {
String temp =
uniqueWords[j];
uniqueWords[j] =
uniqueWords[j+1];
uniqueWords[j+1] = temp
;
int temp1 =
countWords[j];
countWords[j] =
countWords[j+1];
countWords[j+1] = temp1
;
}
}
}
return uniqueWords;
}
public static void main(String[] args) {
// TODO Auto-generated method
stub
String arr[] =
{"hello","hola","hello","hello","ciao","hola","hola","hola"};
System.out.println("The array is
:");
System.out.println(arr);
for(String word:arr)
System.out.print(" "+word+" ");
System.out.println("");
System.out.println("After sorting
by the frequency the array is:");
String sortedArr[] =
sortByFrequency(arr);
for(String word:sortedArr)
System.out.print(" "+word+" ");
}
}
OUTPUT: