Quantcast
Channel: DaniWeb Solved Topics
Viewing all articles
Browse latest Browse all 582

Sort according to frequency

$
0
0
    //With this method, I input a string and return an array that contains a sorted list of characters as per the frequency. Eg: If i input "apple", the out put should be p,a,l,e, How do I do this?

   public static ArrayList<Character> characterFreqDist(String statement)
{
  char[] Array = statement.toCharArray();
  int length = Array.length;
  int most_frequent_count = 0;
  char most_freq_character = '\0';
  char[] Final_Array = new char[length];

  ArrayList<Character> Sorted_Array = new ArrayList<Character>();

  for(int loop = 0 ; loop<length ; loop++)
  {
      most_freq_character = '\0';
      most_frequent_count = 0;
  for(int i = 0; i<length ; i++)
        { 
            char single_character = Array[i] ;

            int counter = 0;

            for(int j = 0; j<length ; j++)
            {
                if (single_character == Array[j])
                {
                    counter++;
                } 
            }
                if (counter > most_frequent_count)
                {
                    most_frequent_count = counter;
                    most_freq_character = single_character;
                }                   

      }

      Sorted_Array.add(most_freq_character);

                int index = 0;
                for (int k = 0; k < length; k++)
                {
                    if(Array[k] != most_freq_character)
                    Final_Array[index++] = Array[k];
                }

      Array =  Final_Array.clone();

      length = Array.length;

    }
    return Sorted_Array;
}

Viewing all articles
Browse latest Browse all 582

Latest Images

Trending Articles



Latest Images