-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort.java
More file actions
42 lines (39 loc) · 1.18 KB
/
CountingSort.java
File metadata and controls
42 lines (39 loc) · 1.18 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
package dip107;
public class CountingSort implements SortingAlgorithm{
@Override
public void sort(int[] arr, int order){
sortModified(arr, order);
}
public static void sortModified(int[] arr, int order) {
int min = Integer.MAX_VALUE / 2, max = Integer.MIN_VALUE / 2;
for (int i = 0; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i];
}
if (max < arr[i]) {
max = arr[i];
}
}
int[] extra = new int[max - min + 1];
for (int i = 0; i < arr.length; i++) {
extra[arr[i] - min]++;
}
if (order == 1) {
int q = 0;
for (int i = 0; i < extra.length; i++) {
for (int j = 0; j < extra[i]; j++) {
arr[q] = min + i;
q++;
}
}
} else {
int q = arr.length - 1;
for (int i = 0; i < extra.length; i++) {
for (int j = 0; j < extra[i]; j++) {
arr[q] = min + i;
q--;
}
}
}
}
}