-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathcountsort.java
49 lines (40 loc) · 972 Bytes
/
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
import java.util.Arrays;
class CountingSort {
void countSort(int arr[], int n) {
int[] arr1 = new int[n + 1];
int x = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > x)
x = arr[i];
}
int[] count_arr = new int[x + 1];
for (int i = 0; i < x; ++i) {
count_arr[i] = 0;
}
for (int i = 0; i < n; i++) {
count_arr[arr[i]]++;
}
for (int i = 1; i <= x; i++) {
count_arr[i] += count_arr[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
arr1[count_arr[arr[i]] - 1] = arr[i];
count_arr[arr[i]]--;
}
for (int i = 0; i < n; i++) {
arr[i] = arr1[i];
}
}
void display(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
public static void main(String args[]) {
int[] arr = { 4, 2, 2, 8, 3, 3, 1 };
int n = arr.length;
CountingSort cs = new CountingSort();
cs.countSort(arr, n);
cs.display(arr);
}
}