-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCountingSort.java
97 lines (86 loc) · 2.75 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
93
94
95
96
97
/**
* Class with 2 ways of doing Counting sort, one naive way and one "better" way
*
* @author Akhil Batra, Alexander Hwang
*
**/
public class CountingSort {
/**
* Counting sort on the given int array. Returns a sorted version of the array.
* Does not touch original array (non-destructive method).
* DISCLAIMER: this method does not always work, find a case where it fails
*
* @param arr int array that will be sorted
* @return the sorted array
*/
public static int[] naiveCountingSort(int[] arr) {
// find max
int max = Integer.MIN_VALUE;
for (int i : arr) {
max = max > i ? max : i;
}
// gather all the counts for each value
int[] counts = new int[max + 1];
for (int i : arr) {
counts[i]++;
}
// when we're dealing with ints, we can just put each value
// count number of times into the new array
int[] sorted = new int[arr.length];
int k = 0;
for (int i = 0; i < counts.length; i += 1) {
for (int j = 0; j < counts[i]; j += 1, k += 1) {
sorted[k] = i;
}
}
// however, below is a more proper, generalized implementation of
// counting sort that uses start position calculation
int[] starts = new int[max + 1];
int pos = 0;
for (int i = 0; i < starts.length; i += 1) {
starts[i] = pos;
pos += counts[i];
}
int[] sorted2 = new int[arr.length];
for (int i = 0; i < arr.length; i += 1) {
int item = arr[i];
int place = starts[item];
sorted2[place] = item;
starts[item] += 1;
}
// return the sorted array
return sorted;
}
/**
* Counting sort on the given int array, must work even with negative numbers.
* Note, this code does not need to work for ranges of numbers greater
* than 2 billion.
* Does not touch original array (non-destructive method).
*
* @param arr int array that will be sorted
*/
public static int[] betterCountingSort(int[] arr) {
if (arr.length == 0) {
return arr;
}
int max = arr[0];
int min = arr[0];
for (int num : arr) {
if (num > max) max = num;
if (num < min) min = num;
}
int[] count = new int[max - min + 1];
for (int num : arr) {
count[num - min]++;
}
int[] sorted = new int[arr.length];
int index = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
sorted[index++] = i + min;
count[i]--;
}
}
return sorted;
}
}