-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountingSort.java
35 lines (32 loc) · 904 Bytes
/
CountingSort.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
public class CountingSort {
public static void counting_sort(int arr[]) {
int largest = Integer.MIN_VALUE;
for(int i = 0; i<arr.length; i++) {
largest = Math.max(largest, arr[i]);
}
int count[] = new int[largest+1];
for(int i = 0; i<arr.length; i++) {
count[arr[i]]++;
}
int j = 0;
for(int i = 0; i<count.length; i++) {
while(count[i]>0) {
arr[j] = i;
j++;
count[i]--;
}
}
}
//for print array
public static void printArr(int arr[]) {
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String args[]) {
int arr[] = {1, 4, 1, 3, 2, 4, 3, 7};
counting_sort(arr);
printArr(arr);
}
}