-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCOUNTING_SORT.java
More file actions
34 lines (31 loc) · 929 Bytes
/
COUNTING_SORT.java
File metadata and controls
34 lines (31 loc) · 929 Bytes
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
import java.util.*;
public class COUNTING_SORT {
public static void countingSort(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
int[] count = new int[max + 1];
for (int i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
for (int i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
int[] sorted = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
sorted[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (int i = 0; i < arr.length; i++) {
arr[i] = sorted[i];
}
}
public static void main(String args[]) {
int arr[] = { 5, 4, 1, 3, 2 };
countingSort(arr);
Printarray(arr);
}
}