- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathCountSort.java
66 lines (51 loc) · 1.54 KB
/
CountSort.java
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
importjava.util.Arrays;
importjava.util.Scanner;
publicclassCountSort {
publicstaticvoidmain(String[] args) {
// This algorithm is preferred for single digit number
System.out.println("Counting Sort : ");
System.out.print("Enter the size of array : ");
try (Scannersc = newScanner(System.in)) {
intn = sc.nextInt();
inta[] = newint[n];
System.out.println("Enter elements : ");
for (inti = 0; i < n; i++) {
a[i] = sc.nextInt();
}
System.out.println("Array before sorting : " + Arrays.toString(a));
countSort(a); // calling the function
System.out.println("\nArray after sorting : " + Arrays.toString(a));
}
// Time Complexity : O(n+k+n+n) = O(n+k)
// if we consider k as content then O(n) -> Linear Time :)
// Space Complexity : O(n+k)
}
privatestaticvoidcountSort(inta[]) {
intk = getMax(a); // to get maximum element for making count array
intcount[] = newint[k + 1]; // to fill frequency of element
for (inti = 0; i < a.length; i++) {
count[a[i]]++;
}
// to reflect position in count array
// similar to filling cumulative frequency
for (inti = 1; i <= k; i++) {
count[i] = count[i] + count[i - 1];
}
// to put element at it's correct position
intb[] = newint[a.length];
for (inti = b.length - 1; i >= 0; i--) {
b[--count[a[i]]] = a[i];
}
// copying elements to a
for (inti = 0; i < a.length; i++)
a[i] = b[i];
}
privatestaticintgetMax(int[] a) {
intmax = Integer.MIN_VALUE;
for (inti : a) {
if (i > max)
max = i;
}
returnmax;
}
}