-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort.java
More file actions
51 lines (42 loc) · 1.17 KB
/
CountingSort.java
File metadata and controls
51 lines (42 loc) · 1.17 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
public class CountingSort {
// This only works for postive values;
public static void Csort(int arr[]) {
int n = arr.length;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
largest = Math.max(largest, arr[i]);
}
int count[] = new int[largest + 1];
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
// Sorting
int j = 0;
for (int i = 0; i <=largest; i++) {
while (count[i] > 0) {
arr[j] = i;
j++;
count[i]--;
}
}
}
// Time Complexity:
// Finding the largest element: O(n)
// Populating the count array: O(n)
// Reconstructing the sorted array: O(n+k), where k is the largest element.
// Overall: O(n+k)
// Space Complexity:
// The count array: O(k)
// Overall: O(k)
public static void main(String[] args) {
int ar[] = { 5, 4, 1, 3, 2 };
for (int num : ar) {
System.out.print(num + " ");
}
System.out.println();
Csort(ar);
for (int num : ar) {
System.out.print(num + " ");
}
}
}