-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortArray_in DescOrder_Of_Frequency.java
More file actions
70 lines (46 loc) · 1.02 KB
/
SortArray_in DescOrder_Of_Frequency.java
File metadata and controls
70 lines (46 loc) · 1.02 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
68
69
// Java program to sort an array in
// decreasing order of their frequency
import java.util.*;
class Solution{
static int sortByFreq(Integer []arr, int n)
{
/
int maxE = -1;
for (int i = 0; i < n; i++) {
maxE = Math.max(maxE, arr[i]);
}
int freq[] = new int[maxE + 1];
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
}
int cnt = 0;
for (int i = 0; i <= maxE; i++) {
if (freq[i] > 0) {
int value = 100000 - i;
arr[cnt] = 100000 * freq[i] + value;
cnt++;
}
}
return cnt;
}
static void printSortedArray(Integer []arr, int cnt)
{
for (int i = 0; i < cnt; i++) {
int frequency = arr[i] / 100000;
int value = 100000 - (arr[i] % 100000);
for (int j = 0; j < frequency; j++) {
System.out.print(value + " ");
}
}
}
public static void main(String[] args)
{
Integer arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 };
int n = arr.length;
int cnt = sortByFreq(arr, n);
Arrays.sort(arr, Collections.reverseOrder());
printSortedArray(arr, cnt);
}
}
/**
* @author Pradumn Patel */