Given an array of integers, sort the array according to frequency of elements. If frequencies of two elements are same, print them in increasing order. Examples:
Input : arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}
Output : 3 3 3 3 2 2 2 12 12 4 5
Explanation :
No. Freq
2 : 3
3 : 4
4 : 1
5 : 1
12 : 2
We have discussed different approaches in below posts : Sort elements by frequency | Set 1 Sort elements by frequency | Set 2 We can solve this problem using map and pairs. Initially we create a map such that map[element] = freq. Once we are done building the map, we create an array of pairs. A pair which stores elements and their corresponding frequency will be used for the purpose of sorting. We write a custom compare function which compares two pairs firstly on the basis of freq and if there is a tie on the basis of values.
Below is its c++ implementation :
C++
#include <bits/stdc++.h>
using namespace std;
bool compare(pair< int , int > &p1,
pair< int , int > &p2)
{
if (p1.second == p2.second)
return p1.first < p2.first;
return p1.second > p2.second;
}
void printSorted( int arr[], int n)
{
map< int , int > m;
for ( int i = 0; i < n; i++)
m[arr[i]]++;
int s = m.size();
pair< int , int > p[s];
int i = 0;
for ( auto it = m.begin(); it != m.end(); ++it)
p[i++] = make_pair(it->first, it->second);
sort(p, p + s, compare);
cout << "Elements sorted by frequency are: " ;
for ( int i = 0; i < s; i++)
{
int freq = p[i].second;
while (freq--)
cout << p[i].first << " " ;
}
}
int main()
{
int arr[] = {2, 3, 2, 4, 5, 12, 2, 3,
3, 3, 12};
int n = sizeof (arr)/ sizeof (arr[0]);
printSorted(arr, n);
return 0;
}
|
Java
import java.util.*;
public class Main
{
static boolean compare(Map.Entry<Integer, Integer> p1,
Map.Entry<Integer, Integer> p2)
{
if (p1.getValue().equals(p2.getValue()))
return p1.getKey() < p2.getKey();
return p1.getValue() > p2.getValue();
}
static void printSorted( int [] arr, int n)
{
Map<Integer, Integer> m
= new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++)
m.put(arr[i], m.getOrDefault(arr[i], 0 ) + 1 );
int s = m.size();
List<Map.Entry<Integer, Integer> > list
= new ArrayList<Map.Entry<Integer, Integer> >(
m.entrySet());
Collections.sort(
list, (p1, p2) -> compare(p1, p2) ? - 1 : 1 );
System.out.print(
"Elements sorted by frequency are: " );
for (Map.Entry<Integer, Integer> entry : list) {
int freq = entry.getValue();
while (freq-- > 0 )
System.out.print(entry.getKey() + " " );
}
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , 2 , 4 , 5 , 12 , 2 , 3 , 3 , 3 , 12 };
int n = arr.length;
printSorted(arr, n);
}
}
|
Python3
from collections import Counter
def compare(x, y):
if x[ 1 ] = = y[ 1 ]:
return x[ 0 ] < y[ 0 ]
return x[ 1 ] > y[ 1 ]
def printSorted(arr, n):
m = Counter(arr)
s = len (m)
p = [(k, v) for k, v in m.items()]
p = sorted (p, key = lambda x: compare(x, x))
print ( "Elements sorted by frequency are: " , end = '')
for i in range (s):
freq = p[i][ 1 ]
while freq > 0 :
print (p[i][ 0 ], end = ' ' )
freq - = 1
arr = [ 2 , 3 , 2 , 4 , 5 , 12 , 2 , 3 , 3 , 3 , 12 ]
n = len (arr)
printSorted(arr, n)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass
{
static bool compare(KeyValuePair< int , int > p1, KeyValuePair< int , int > p2)
{
if (p1.Value == p2.Value)
return p1.Key < p2.Key;
return p1.Value > p2.Value;
}
static void printSorted( int [] arr, int n)
{
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
if (m.ContainsKey(arr[i]))
m[arr[i]]++;
else
m[arr[i]] = 1;
}
int s = m.Count;
List<KeyValuePair< int , int >> list =
new List<KeyValuePair< int , int >>(m);
list.Sort((p1, p2) => compare(p1, p2) ? -1 : 1);
Console.Write( "Elements sorted by frequency are: " );
foreach (KeyValuePair< int , int > entry in list)
{
int freq = entry.Value;
while (freq-- > 0)
Console.Write(entry.Key + " " );
}
}
public static void Main( string [] args)
{
int [] arr = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
int n = arr.Length;
printSorted(arr, n);
}
}
|
Javascript
function compare(p1, p2)
{
if (p1[1] == p2[1]) {
return p1[0] < p2[0];
}
return p1[1] > p2[1];
}
function printSorted(arr)
{
let m = new Map();
for (let i = 0; i < arr.length; i++) {
if (m.has(arr[i])) {
m.set(arr[i], m.get(arr[i]) + 1);
} else {
m.set(arr[i], 1);
}
}
let s = m.size;
let p = new Array(s);
let i = 0;
for (let [key, value] of m) {
p[i] = [key, value];
i++;
}
for (let i = 1; i < s; i++) {
let j = i - 1;
let key = p[i];
while (j >= 0 && compare(p[j], key)) {
p[j + 1] = p[j];
j = j - 1;
}
p[j + 1] = key;
}
process.stdout.write( "Elements sorted by frequency are: " );
for (let i = s-1; i >= 0; i--) {
let freq = p[i][1];
while (freq--) {
process.stdout.write(p[i][0] + " " );
}
}
}
let arr = [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12];
printSorted(arr);
|
Output
Elements sorted by frequency are: 3 3 3 3 2 2 2 12 12 4 5
Time Complexity : O(n Log n)
Space Complexity: O(n)
The above algorithm requires O(n) space for the hash map and the array of pairs.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!