Sorting Elements of an Array by Frequency

PROBLEM :

Given an array of integers, sort the array according to frequency of elements. For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}, then modify the array to {3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}.

If frequencies of two elements are same, print them in increasing order.



Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.


Output:
Print each sorted array in a seperate line. For each array its numbers should be seperated by space.


Constraints:
1 = T = 70
30 = N = 130
1 = A [ i ] = 60


Example:
Input:
1
5
5 5 4 6 4

Output:
4 4 5 5 6

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :(Using Auxilary arry)
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
void Array_by_Frequency(int [],int ) ;
int main()
 {
int t,no,arr[200],i ;
cin>>t ;
while(t--)
{
   cin>>no ;
   for(i=0;i<no;i++)
       cin>>arr[i] ;
 
    Array_by_Frequency(arr,no) ;
   
    for(i=0;i<no;i++)
       cout<<arr[i]<<" " ;
    cout<<endl ;
}
return 0;
}

void Array_by_Frequency(int arr[],int no)
{
    int i,max,ele,k ;
    int hash[200]={0} ;
    int b[200] ;
   
    for(i=0;i<no;i++)
        hash[arr[i]]++ ;
 
    max=-1 ;
    ele=-1 ;
    k=0 ;
   
    lable :
    for(i=0;i<no;i++)
    {
        if(hash[arr[i]]>=max)
        {
            if(hash[arr[i]]==max&&arr[i]<ele)
            {
                max=hash[arr[i]] ;
                ele=arr[i] ;
            }
            else if(hash[arr[i]]>max)
            {
                max=hash[arr[i]] ;
                ele=arr[i] ;
            }
        }
    }
   
    for(i=k;i<max+k;i++)
    b[i]=ele ;
   
k=i ;
     
    hash[ele]=-1 ;
    ele=-1 ;
    max=0 ;
   
    if(k<no)
        goto lable ;
       
    for(i=0;i<no;i++)
    arr[i]=b[i] ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )