-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathCountingSort.java
92 lines (83 loc) · 2.2 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Copyright 2022 jingedawang
*/
package sort;
import utils.ArrayPrinter;
import utils.ArrayGenerator;
/**
* Counting sort algorithm.
*/
public class CountingSort implements Sort {
/**
* Demo code.
*/
public static void main(String[] args) {
// The elements to be sorted by counting sort must lies in [0, k).
int k = 10;
int[] arr = ArrayGenerator.randomArray(k);
System.out.println("Original array:");
ArrayPrinter.print(arr);
Sort sort = new CountingSort(k);
sort.sort(arr);
System.out.println();
System.out.println("Sorted by counting sort:");
ArrayPrinter.print(arr);
}
/**
* Constructor with {@code k} specified.
*
* @param k The upper limit of the array elements.
*/
public CountingSort(int k) {
this.k = k;
}
/**
* Counting sort.
*
* @param arr Integer array to be sorted.
*/
@Override
public void sort(int[] arr) {
int[] sortedArr = new int[arr.length];
countingSort(arr, sortedArr, k);
System.arraycopy(sortedArr, 0, arr, 0, sortedArr.length);
}
/**
* Counting sort.
*
* @param arr The array to be sorted.
* @param sortedArr The sorted array.
* @param k The upper limit of the array elements.
*/
public void countingSort(int[] arr, int[] sortedArr, int k) {
countingSortWithIndices(arr, sortedArr, k, null);
}
/**
* Counting sort with indices.
*
* @param arr The array to be sorted.
* @param sortedArr The sorted array.
* @param k The upper limit of the array elements.
* @param indices The indices of the sorted elements in original array.
*/
public void countingSortWithIndices(int[] arr, int[] sortedArr, int k, int[] indices) {
int[] countingArr = new int[k];
for (int item : arr) {
countingArr[item]++;
}
// countingArr[i] now contains the number of elements equal to i.
for (int i = 1; i < k; i++) {
countingArr[i] += countingArr[i - 1];
}
//countingArr[i] now contains the number of elements less than or equal to i.
for (int i = arr.length - 1; i >= 0; i--) {
sortedArr[countingArr[arr[i]] - 1] = arr[i];
if (indices != null) {
indices[countingArr[arr[i]] - 1] = i;
}
countingArr[arr[i]]--;
}
}
// The upper limit of the array elements.
private final int k;
}