Given an array of integers arr[], sort the array according to the frequency of elements, i.e. elements that have higher frequency come first. If the frequencies of two elements are the same, then the smaller number comes first.
Examples:
Input: arr[] = [5, 5, 4, 6, 4]
Output: [4, 4, 5, 5, 6]
Explanation: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are the same the smaller element comes first. So 4 comes first then comes 5. Finally comes 6. The output is 4 4 5 5 6.Input: arr[] = [9, 9, 9, 2, 5]
Output: [9, 9, 9, 2, 5]
Explanation: The highest frequency here is 3. Element 9 has the highest frequency So 9 comes first. Now both 2 and 5 have the same frequency. So we print smaller elements first. The output is 9 9 9 2 5.
Table of Content
Sorting - O(n * log n) Time and O(n) Space
The idea is to use sorting to arrange the similar elements together, the count frequencies using linear traversal.
- Store frequencies and items in a 2d array of elements.
- Finally sort this 2d array according to the frequency of each element.
Let us understand with an example:
Input: arr[] = [2, 5, 2, 8, 5, 6, 8, 8]
Step1: Sort the array,
After sorting we get: 2 2 5 5 6 8 8 8
Step 2: Now construct the 2D array to maintain the count of every element as {freq, element}
{{2, 2}, {2, 5}, {1, 6}, {3, 8}}
Step 3: Sort the array by count
{{3, 8}, {2, 2}, {2, 5}, {1, 6}}
Step 4: Construct the result array by adding each element according to its frequency.
ans[] = {8, 8, 8, 2, 2, 5, 5, 6}.
#include
using namespace std;
vector<int> sortByFreq(vector<int> &arr) {
int n = arr.size();
// sort the array first
sort(arr.begin(), arr.end());
// create a 2d vector to store
// the frequency of each element
vector<vector<int>> freq;
// to sort the frequency in descending order
auto comp = [&](vector<int> &a, vector<int> &b)
{
if (a[0] == b[0])
return a[1] < b[1];
return a[0] > b[0];
};
for(int i = 0; i < n; i++) {
// to store the frequency
int cnt = 1;
while(i < n - 1 && arr[i] == arr[i + 1]) {
cnt++;
i++;
}
// push the frequency and the element
freq.push_back({cnt, arr[i]});
}
// sort the frequency array
sort(freq.begin(), freq.end(), comp);
// to store the answer
vector<int> ans;
// push the elements in the answer array
for(int i = 0; i < freq.size(); i++) {
for(int j = 0; j < freq[i][0]; j++) {
ans.push_back(freq[i][1]);
}
}
return ans;
}
int main() {
vector<int> arr = {5, 5, 4, 6, 4};
vector<int> ans = sortByFreq(arr);
for(int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
return 0;
}
import java.util.*;
class GFG {
// Function to sort the array
// according to frequency of elements
static ArrayList<Integer> sortByFreq(int[] arr) {
int n = arr.length;
// sort the array first
Arrays.sort(arr);
// create a 2d vector to store
// the frequency of each element
ArrayList<ArrayList<Integer>> freq = new ArrayList<>();
// to sort the frequency in descending order
Comparator<ArrayList<Integer>> comp =
new Comparator<ArrayList<Integer>>() {
public int compare(ArrayList<Integer> a,
ArrayList<Integer> b) {
if(a.get(0).equals(b.get(0)))
return a.get(1) - b.get(1);
return b.get(0) - a.get(0);
}
};
for (int i = 0; i < n; i++) {
// to store the frequency
int cnt = 1;
while(i < n - 1 && arr[i] == arr[i + 1]) {
cnt++;
i++;
}
// push the frequency and the element
ArrayList<Integer> temp = new ArrayList<>();
temp.add(cnt);
temp.add(arr[i]);
freq.add(temp);
}
// sort the frequency array
Collections.sort(freq, comp);
// to store the answer
ArrayList<Integer> ans = new ArrayList<>();
// push the elements in the answer array
for (int i = 0; i < freq.size(); i++) {
int count = freq.get(i).get(0);
int value = freq.get(i).get(1);
for (int j = 0; j < count; j++) {
ans.add(value);
}
}
return ans;
}
public static void main(String[] args) {
int[] arr = {5, 5, 4, 6, 4};
ArrayList<Integer> ans = sortByFreq(arr);
for (int i = 0; i < ans.size(); i++) {
System.out.print(ans.get(i) + " ");
}
}
}
def sortByFreq(arr):
n = len(arr)
# sort the array first
arr.sort()
# create a 2d vector to store
# the frequency of each element
freq = []
# to sort the frequency in descending order
i = 0
while i < n:
cnt = 1
while i < n - 1 and arr[i] == arr[i + 1]:
cnt += 1
i += 1
freq.append([cnt, arr[i]])
i += 1
freq.sort(key=lambda a: (-a[0], a[1]))
# to store the answer
ans = []
# push the elements in the answer array
for i in range(len(freq)):
for j in range(freq[i][0]):
ans.append(freq[i][1])
return ans
if __name__ == "__main__":
arr = [5, 5, 4, 6, 4]
ans = sortByFreq(arr)
for i in ans:
print(i, end=" ")
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
// Function to sort the array
// according to frequency of elements
static List<int> sortByFreq(int[] arr) {
int n = arr.Length;
// sort the array first
Array.Sort(arr);
// create a 2d vector to store
// the frequency of each element
List<List<int>> freq = new List<List<int>>();
// to sort the frequency in descending order
for (int i = 0; i < n; i++) {
int cnt = 1;
while (i < n - 1 && arr[i] == arr[i + 1]) {
cnt++;
i++;
}
freq.Add(new List<int> { cnt, arr[i] });
}
freq.Sort((a, b) => {
if(a[0] == b[0])
return a[1].CompareTo(b[1]);
return b[0].CompareTo(a[0]);
});
// to store the answer
List<int> ans = new List<int>();
// push the elements in the answer array
for (int i = 0; i < freq.Count; i++) {
int count = freq[i][0];
int value = freq[i][1];
for (int j = 0; j < count; j++) {
ans.Add(value);
}
}
return ans;
}
static void Main() {
int[] arr = {5, 5, 4, 6, 4};
List<int> ans = sortByFreq(arr);
foreach (int i in ans) {
Console.Write(i + " ");
}
}
}
function sortByFreq(arr) {
// sort the array first
arr.sort((a, b) => a - b);
// create a 2d vector to store
// the frequency of each element
let freq = [];
let n = arr.length;
for (let i = 0; i < n; i++) {
let cnt = 1;
while (i < n - 1 && arr[i] === arr[i + 1]) {
cnt++;
i++;
}
freq.push([cnt, arr[i]]);
}
// to sort the frequency in descending order
freq.sort((a, b) => {
if (a[0] === b[0])
return a[1] - b[1];
return b[0] - a[0];
});
// to store the answer
let ans = [];
// push the elements in the answer array
for (let i = 0; i < freq.length; i++) {
for (let j = 0; j < freq[i][0]; j++) {
ans.push(freq[i][1]);
}
}
return ans;
}
let arr = [5, 5, 4, 6, 4];
let ans = sortByFreq(arr);
console.log(ans.join(" "));
Output
4 4 5 5 6
Hashing and Sorting - O(n * log n) Time and O(n) Space
The idea is to store the count of each element in a Hash Map, and then create the frequency array similar to above approach.
After above the remaining two steps are same as above approach.
- Store frequencies and items in a 2d array of elements.
- Finally sort this 2d array according to the frequency of each element.
#include
using namespace std;
vector<int> sortByFreq(vector<int> &arr) {
int n = arr.size();
// hash map to store the
// frequency of each element
unordered_map<int, int> mp;
// store the frequency of each element
for(int i = 0; i < n; i++) {
mp[arr[i]]++;
}
// create a 2d vector to store
// the frequency of each element
vector<vector<int>> freq;
// to sort the frequency in descending order
auto comp = [&](vector<int> &a, vector<int> &b)
{
if (a[0] == b[0])
return a[1] < b[1];
return a[0] > b[0];
};
// store the frequency and the element
for(auto i : mp) {
freq.push_back({i.second, i.first});
}
// sort the frequency array
sort(freq.begin(), freq.end(), comp);
// to store the answer
vector<int> ans;
// push the elements in the answer array
for(int i = 0; i < freq.size(); i++) {
for(int j = 0; j < freq[i][0]; j++) {
ans.push_back(freq[i][1]);
}
}
return ans;
}
int main() {
vector<int> arr = {5, 5, 4, 6, 4};
vector<int> ans = sortByFreq(arr);
for(int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
return 0;
}
import java.util.*;
class GFG {
// Function to sort the array
// according to frequency of elements
static ArrayList<Integer> sortByFreq(int[] arr) {
int n = arr.length;
// hash map to store the
// frequency of each element
HashMap<Integer, Integer> mp = new HashMap<>();
// store the frequency of each element
for (int i = 0; i < n; i++) {
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
}
// create a 2d vector to store
// the frequency of each element
ArrayList<ArrayList<Integer>> freq = new ArrayList<>();
// store the frequency and the element
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(entry.getValue());
temp.add(entry.getKey());
freq.add(temp);
}
// to sort the frequency in descending order
Collections.sort(freq, new Comparator<ArrayList<Integer>>() {
public int compare(ArrayList<Integer> a, ArrayList<Integer> b) {
if(a.get(0).equals(b.get(0)))
return a.get(1) - b.get(1);
return b.get(0) - a.get(0);
}
});
// to store the answer
ArrayList<Integer> ans = new ArrayList<>();
// push the elements in the answer array
for (int i = 0; i < freq.size(); i++) {
int count = freq.get(i).get(0);
int value = freq.get(i).get(1);
for (int j = 0; j < count; j++) {
ans.add(value);
}
}
return ans;
}
public static void main(String[] args) {
int[] arr = {5, 5, 4, 6, 4};
ArrayList<Integer> ans = sortByFreq(arr);
for (int i = 0; i < ans.size(); i++) {
System.out.print(ans.get(i) + " ");
}
}
}
def sortByFreq(arr):
n = len(arr)
# hash map to store the
# frequency of each element
mp = {}
# store the frequency of each element
for i in range(n):
if arr[i] in mp:
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
# create a 2d vector to store
# the frequency of each element
freq = []
# store the frequency and the element
for key, value in mp.items():
freq.append([value, key])
# to sort the frequency in descending order
freq.sort(key=lambda a: (-a[0], a[1]))
# to store the answer
ans = []
# push the elements in the answer array
for i in range(len(freq)):
for j in range(freq[i][0]):
ans.append(freq[i][1])
return ans
if __name__ == "__main__":
arr = [5, 5, 4, 6, 4]
ans = sortByFreq(arr)
for i in range(len(ans)):
print(ans[i], end=" ")
using System;
using System.Collections.Generic;
class GfG {
// Function to sort the array
// according to frequency of elements
static List<int> sortByFreq(int[] arr) {
int n = arr.Length;
// hash map to store the
// frequency of each element
Dictionary<int, int> mp = new Dictionary<int, int>();
// store the frequency of each element
for (int i = 0; i < n; i++) {
if (mp.ContainsKey(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
// create a 2d vector to store
// the frequency of each element
List<List<int>> freq = new List<List<int>>();
// store the frequency and the element
foreach (var kvp in mp) {
List<int> temp = new List<int> { kvp.Value, kvp.Key };
freq.Add(temp);
}
// to sort the frequency in descending order
freq.Sort((a, b) => {
if(a[0] == b[0])
return a[1].CompareTo(b[1]);
return b[0].CompareTo(a[0]);
});
// to store the answer
List<int> ans = new List<int>();
// push the elements in the answer array
for (int i = 0; i < freq.Count; i++) {
int count = freq[i][0];
int value = freq[i][1];
for (int j = 0; j < count; j++) {
ans.Add(value);
}
}
return ans;
}
static void Main() {
int[] arr = {5, 5, 4, 6, 4};
List<int> ans = sortByFreq(arr);
foreach (int i in ans) {
Console.Write(i + " ");
}
}
}
function sortByFreq(arr)
{
// hash map to store the
// frequency of each element
let mp = {};
let n = arr.length;
// store the frequency of each element
for (let i = 0; i < n; i++) {
if (mp.hasOwnProperty(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
// create a 2d vector to store
// the frequency of each element
let freq = [];
for (let key in mp) {
freq.push([ mp[key], parseInt(key) ]);
}
// to sort the frequency in descending order
freq.sort((a, b) => {
if (a[0] === b[0])
return a[1] - b[1];
return b[0] - a[0];
});
// to store the answer
let ans = [];
// push the elements in the answer array
for (let i = 0; i < freq.length; i++) {
for (let j = 0; j < freq[i][0]; j++) {
ans.push(freq[i][1]);
}
}
return ans;
}
// Driver Code
let arr = [ 5, 5, 4, 6, 4 ];
let ans = sortByFreq(arr);
console.log(ans.join(" "));
Output
4 4 5 5 6
Self Balancing Binary Search Tree - O(n * log n) Time and O(n) Space
The idea is to use a self-balancing binary search tree (AVL Tree or Red-Black Tree) to efficiently store the elements and their frequency in the form of tree nodes.
Follow the below given steps:
- Create a Binary Search Tree (BST) and, as you insert each element, maintain a count (frequency) of that element in the same BST.
- Perform an inorder traversal of the BST. During the traversal, store each unique element along with its frequency as a pair in an auxiliary array called freq[].
- Sort the freq[] array according to the frequency of the elements.
- Traverse through the sorted count[] array and, for each element x with frequency freq, print x exactly freq times.
C++, Java and C# have built-in implementations of self-balancing BSTs. For Python and JavaScript, we implement an AVL Tree.
#include
#include
#include
#include
using namespace std;
// Function to sort the array according to frequency
vector<int> sortByFreq(vector<int> &arr)
{
int n = arr.size();
// Map stores elements in a self-balancing BST
map<int, int> mp;
// Store the frequency of each element
for (int i = 0; i < n; i++)
mp[arr[i]]++;
// Store frequency and element
vector<vector<int>> freq;
for (auto it : mp)
freq.push_back({it.second, it.first});
// Sort by frequency in descending order
// If frequency is same, sort by value in ascending order
sort(freq.begin(), freq.end(), [](vector<int> &a, vector<int> &b) {
if (a[0] == b[0])
return a[1] < b[1];
return a[0] > b[0];
});
// Store the answer
vector<int> res;
for (auto &it : freq)
{
for (int j = 0; j < it[0]; j++)
res.push_back(it[1]);
}
return res;
}
int main()
{
vector<int> arr = {5, 5, 4, 6, 4};
vector<int> ans = sortByFreq(arr);
for (int x : ans)
cout << x << " ";
return 0;
}
import java.util.*;
class GFG {
// Function to sort the array according to frequency
public ArrayList<Integer> sortByFreq(int[] arr)
{
int n = arr.length;
// Map stores elements in a self-balancing BST
TreeMap<Integer, Integer> mp = new TreeMap<>();
// Store the frequency of each element
for (int i = 0; i < n; i++)
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
// Store frequency and element
ArrayList<int[]> freq = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry :
mp.entrySet())
freq.add(new int[] { entry.getValue(),
entry.getKey() });
// Sort by frequency in descending order
// If frequency is same, sort by value in ascending
// order
freq.sort((a, b) -> {
if (a[0] == b[0])
return Integer.compare(a[1], b[1]);
return Integer.compare(b[0], a[0]);
});
// Store the answer
ArrayList<Integer> res = new ArrayList<>();
// Add each element according to its frequency
for (int[] it : freq) {
for (int j = 0; j < it[0]; j++)
res.add(it[1]);
}
return res;
}
public static void main(String[] args)
{
int[] arr = { 5, 5, 4, 6, 4 };
ArrayList<Integer> ans = new GFG().sortByFreq(arr);
for (int x : ans)
System.out.print(x + " ");
}
}
def sortByFreq(arr):
# Sort the array so equal elements are together.
arr.sort()
# AVL tree arrays
key = []
freq = []
left = []
right = []
height = []
def newNode(x, f):
i = len(key)
key.append(x)
freq.append(f)
left.append(-1)
right.append(-1)
height.append(1)
return i
def getHeight(x):
return 0 if x == -1 else height[x]
def updateHeight(x):
lh = getHeight(left[x])
rh = getHeight(right[x])
height[x] = max(lh, rh) + 1
def rotateRight(x):
y = left[x]
t = right[y]
right[y] = x
left[x] = t
updateHeight(x)
updateHeight(y)
return y
def rotateLeft(x):
y = right[x]
t = left[y]
left[y] = x
right[x] = t
updateHeight(x)
updateHeight(y)
return y
def insert(root, x, f):
if root == -1:
return newNode(x, f)
if x < key[root]:
left[root] = insert(left[root], x, f)
elif x > key[root]:
right[root] = insert(right[root], x, f)
else:
freq[root] = f
return root
updateHeight(root)
balance = getHeight(left[root]) - getHeight(right[root])
# Left-left
if balance > 1 and x < key[left[root]]:
return rotateRight(root)
# Left-right
if balance > 1 and x > key[left[root]]:
left[root] = rotateLeft(left[root])
return rotateRight(root)
# Right-right
if balance < -1 and x > key[right[root]]:
return rotateLeft(root)
# Right-left
if balance < -1 and x < key[right[root]]:
right[root] = rotateRight(right[root])
return rotateLeft(root)
return root
# Build frequency list from sorted array.
values = []
i = 0
n = len(arr)
while i < n:
j = i + 1
while j < n and arr[j] == arr[i]:
j += 1
values.append((arr[i], j - i))
i = j
# Build the self-balancing BST using distinct elements.
root = -1
for x, f in values:
root = insert(root, x, f)
# Store nodes using inorder traversal.
nodes = []
stack = []
cur = root
while stack or cur != -1:
while cur != -1:
stack.append(cur)
cur = left[cur]
cur = stack.pop()
nodes.append((freq[cur], key[cur]))
cur = right[cur]
# Sort by frequency descending and value ascending.
nodes.sort(key=lambda x: (-x[0], x[1]))
# Build the result.
res = []
for f, x in nodes:
res.extend([x] * f)
return res
if __name__ == '__main__':
arr = [5, 5, 4, 6, 4]
res = sortByFreq(arr)
for x in res:
print(x, end=' ')
using System;
using System.Collections.Generic;
class GFG
{
// Function to sort the array according to frequency
public static List<int> sortByFreq(int[] arr)
{
int n = arr.Length;
// Map stores elements and their frequencies
Dictionary<int, int> mp = new Dictionary<int, int>();
// Store the frequency of each element
for (int i = 0; i < n; i++)
{
if (mp.ContainsKey(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
// Store frequency and element
List<Tuple<int, int>> freq = new List<Tuple<int, int>>();
foreach (var kvp in mp)
freq.Add(new Tuple<int, int>(kvp.Value, kvp.Key));
// Sort by frequency in descending order
// If frequency is same, sort by value in ascending order
freq.Sort((a, b) =>
a.Item1 == b.Item1
? a.Item2.CompareTo(b.Item2)
: b.Item1.CompareTo(a.Item1));
// Store the answer
List<int> res = new List<int>();
foreach (var it in freq)
{
for (int j = 0; j < it.Item1; j++)
res.Add(it.Item2);
}
return res;
}
static void Main()
{
int[] arr = { 5, 5, 4, 6, 4 };
List<int> ans = sortByFreq(arr);
foreach (int x in ans)
Console.Write(x + " ");
}
}
// Function to sort the array according to frequency
function sortByFreq(arr)
{
let n = arr.length;
// Map stores elements in a self-balancing BST
let mp = new Map();
// Store the frequency of each element
for (let i = 0; i < n; i++)
mp.set(arr[i], (mp.get(arr[i]) || 0) + 1);
// Store frequency and element
let freq = [];
for (let [key, value] of mp)
freq.push([ value, key ]);
// Sort by frequency in descending order
// If frequency is same, sort by value in ascending
// order
freq.sort((a, b) => a[0] === b[0] ? a[1] - b[1]
: b[0] - a[0]);
// Store the answer
let res = [];
for (let it of freq) {
for (let j = 0; j < it[0]; j++)
res.push(it[1]);
}
return res;
}
// Driver Code
let arr = [ 5, 5, 4, 6, 4 ];
let ans = sortByFreq(arr);
for (let x of ans)
console.log(x + " ");
Output
4 4 5 5 6
Hash Map and Heap - O(n * log n) Time and O(n) Space
The idea is to firstly create the value - frequency table using the Hash Map, then make a Heap such that high frequency remains at top.
Step by Step Implementation of Approach:
- Take the array and use Hash Map to create value - frequency table
- Then create a heap such that the element with higher frequency remains at the top. If frequencies are equal, the smaller element is given higher priority.
- Store the negative of each element in the heap so that elements with the same frequency are processed in ascending order.
- Then after full insertion into Heap, pop one by one and store it into the array.
#include
using namespace std;
vector<int> sortByFreq(vector<int> &arr)
{
int n = arr.size();
// hash map to store the
// frequency of each element
unordered_map<int, int> mp;
// store the frequency of each element
for (int i = 0; i < n; i++)
{
mp[arr[i]]++;
}
// to store the frequency
// in descending order
priority_queue<vector<int>> pq;
// store the frequency and the element
for (auto i : mp)
{
// storing the negative of element
// to sor the elements with same
// frequency in ascending order
pq.push({i.second, -i.first});
}
// to store the answer
vector<int> ans;
// push the elements in the answer array
while (!pq.empty())
{
int freq = pq.top()[0];
int ele = -pq.top()[1];
pq.pop();
for (int i = 0; i < freq; i++)
{
ans.push_back(ele);
}
}
return ans;
}
int main()
{
vector<int> arr = {5, 5, 4, 6, 4};
vector<int> ans = sortByFreq(arr);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << " ";
}
return 0;
}
import java.util.*;
class GFG {
static ArrayList<Integer> sortByFreq(int[] arr)
{
int n = arr.length;
// Hash map to store the frequency of each element.
HashMap<Integer, Integer> mp = new HashMap<>();
// Store the frequency of each element.
for (int i = 0; i < n; i++) {
mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
}
// Store frequency and element in the heap.
PriorityQueue<int[]> pq =
new PriorityQueue<>(new Comparator<int[]>() {
public int compare(int[] a, int[] b)
{
// Higher frequency comes first.
if (a[0] != b[0])
return b[0] - a[0];
// Smaller element comes first.
return a[1] - b[1];
}
});
// Add frequency and element to the heap.
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
int ele = entry.getKey();
int freq = entry.getValue();
pq.add(new int[] {freq, ele});
}
// Store the answer.
ArrayList<Integer> ans = new ArrayList<>();
// Add elements according to their frequency.
while (!pq.isEmpty()) {
int[] top = pq.poll();
int freq = top[0];
int ele = top[1];
for (int i = 0; i < freq; i++) {
ans.add(ele);
}
}
return ans;
}
public static void main(String[] args)
{
int[] arr = {5, 5, 4, 6, 4};
ArrayList<Integer> ans = sortByFreq(arr);
for (int i = 0; i < ans.size(); i++) {
System.out.print(ans.get(i) + " ");
}
}
}
import heapq
def sortByFreq(arr):
n = len(arr)
# hash map to store the
# frequency of each element
mp = {}
# store the frequency of each element
for i in range(n):
if arr[i] in mp:
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
# to store the frequency
# in descending order
pq = []
# store the frequency and the element
for key, freq in mp.items():
# storing the negative of element
# to sort the elements with same
# frequency in ascending order
heapq.heappush(pq, (-freq, key))
# to store the answer
ans = []
# push the elements in the answer array
while pq:
freq, ele = heapq.heappop(pq)
freq = -freq
for i in range(freq):
ans.append(ele)
return ans
if __name__ == "__main__":
arr = [5, 5, 4, 6, 4]
ans = sortByFreq(arr)
for i in range(len(ans)):
print(ans[i], end=" ")
using System;
using System.Collections.Generic;
class GFG {
// Max heap for storing frequency and element
class MaxHeap {
List<int[]> heap = new List<int[]>();
// Compare two elements
bool Greater(int[] a, int[] b)
{
if (a[0] != b[0])
return a[0] > b[0];
return a[1] > b[1];
}
// Add an element to the heap
public void Push(int[] item)
{
heap.Add(item);
int i = heap.Count - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (!Greater(heap[i], heap[parent]))
break;
int[] temp = heap[i];
heap[i] = heap[parent];
heap[parent] = temp;
i = parent;
}
}
// Remove and return the maximum element
public int[] Pop()
{
int[] res = heap[0];
heap[0] = heap[heap.Count - 1];
heap.RemoveAt(heap.Count - 1);
int i = 0;
while (true) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if (left < heap.Count
&& Greater(heap[left], heap[largest]))
largest = left;
if (right < heap.Count
&& Greater(heap[right], heap[largest]))
largest = right;
if (largest == i)
break;
int[] temp = heap[i];
heap[i] = heap[largest];
heap[largest] = temp;
i = largest;
}
return res;
}
public bool IsEmpty() { return heap.Count == 0; }
}
// Function to sort the array according to frequency of
// elements
public List<int> sortByFreq(int[] arr)
{
int n = arr.Length;
// Hash map to store the frequency of each element
Dictionary<int, int> mp
= new Dictionary<int, int>();
// Store the frequency of each element
for (int i = 0; i < n; i++) {
if (!mp.ContainsKey(arr[i]))
mp[arr[i]] = 0;
mp[arr[i]]++;
}
// Priority queue implemented using max heap
MaxHeap pq = new MaxHeap();
// Store the frequency and the element
foreach(var item in mp)
{
// Store the negative of element
// to sort elements with same
// frequency in ascending order
pq.Push(new int[] { item.Value, -item.Key });
}
// To store the answer
List<int> res = new List<int>();
// Push the elements in the answer array
while (!pq.IsEmpty()) {
int[] top = pq.Pop();
int freq = top[0];
int ele = -top[1];
for (int i = 0; i < freq; i++)
res.Add(ele);
}
return res;
}
public static void Main()
{
int[] arr = { 5, 5, 4, 6, 4 };
List<int> ans = new GFG().sortByFreq(arr);
for (int i = 0; i < ans.Count; i++)
Console.Write(ans[i] + " ");
}
}
function sortByFreq(arr)
{
// Hash map to store the frequency of each element.
let mp = {};
let n = arr.length;
// Store the frequency of each element.
for (let i = 0; i < n; i++) {
if (mp.hasOwnProperty(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
// Store the frequency and the element.
let pq = [];
for (let key in mp) {
let freq = mp[key];
let ele = parseInt(key);
pq.push([ freq, ele ]);
}
// Sort by frequency in descending order.
// If frequency is same, smaller element comes first.
pq.sort((a, b) => {
if (a[0] === b[0])
return a[1] - b[1];
return b[0] - a[0];
});
// Store the answer.
let ans = [];
// Add each element according to its frequency.
while (pq.length > 0) {
let top = pq.shift();
let freq = top[0];
let ele = top[1];
for (let i = 0; i < freq; i++) {
ans.push(ele);
}
}
return ans;
}
// Driver Code
let arr = [ 5, 5, 4, 6, 4 ];
let ans = sortByFreq(arr);
console.log(ans.join(" "));
Output
4 4 5 5 6