#C5908. Frequency Based Sorting
Frequency Based Sorting
Frequency Based Sorting
You are given an array of n integers. Your task is to sort the array according to the following rules:
- Elements with lower frequency come first.
- If two numbers have the same frequency, the smaller number comes first.
Mathematically, let \( f(x) \) denote the frequency of element \( x \) in the array, then for any two elements \( x \) and \( y \),
\( x \) should appear before \( y \) if and only if either
\( f(x) < f(y) \) or \( f(x) = f(y) \) and \( x < y \).
For example, given the array [4, 5, 6, 5, 4, 3]
, the frequency of each element is:
\( f(3)=1, f(4)=2, f(5)=2, f(6)=1 \). Sorting by frequency and value results in [3, 6, 4, 4, 5, 5]
.
inputFormat
The first line contains a single integer n (n is the size of the array).
The second line contains n space-separated integers.
outputFormat
Output a single line with the n integers sorted according to the specified rules, separated by a single space.
## sample6
4 5 6 5 4 3
3 6 4 4 5 5