-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSort an Array
More file actions
67 lines (57 loc) · 1.79 KB
/
Sort an Array
File metadata and controls
67 lines (57 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Sort an array
Send Feedback
Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first.
Input Format:
The first line 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 Format:
Print the soted array seperated by a space.
Example:
Input:
6
1 2 2 2 3 3
Output:
2 2 2 3 3 1
ode in java
***********************************************************
import java.util.*;
public class Solution {
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
int array[]=new int[n];
for(int i=0;i<n;i++)
array[i]=sc.nextInt();
Map<Integer,Integer> map = new HashMap<>();
List<Integer> outputArray = new ArrayList<>();
for(int current : array)
{
int count = map.getOrDefault(current, 0);
map.put(current,count+1);
outputArray.add(current);
}
SortComparator comp =new SortComparator(map);
Collections.sort(outputArray, comp);
for(Integer i : outputArray)
{
System.out.print(i+" ");
}
}
}
class SortComparator implements Comparator<Integer>
{
private final Map<Integer,Integer> freqMap;
SortComparator(Map<Integer,Integer> tFreqMap)
{
this.freqMap = tFreqMap;
}
public int compare(Integer k1, Integer k2)
{
int freqCompare = freqMap.get(k2).compareTo(freqMap.get(k1));
int valueCompare = k1.compareTo(k2);
if(freqCompare==0)
return valueCompare;
else
return freqCompare;
}
}