-
Notifications
You must be signed in to change notification settings - Fork 19
/
CountingSort.java
102 lines (60 loc) · 1.97 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
98
99
100
101
102
package src.java;
import src.java.*;
/**
* Classe que implementa a estratégia de Counting Sort vista em sala. Procure
* evitar desperdicio de memoria alocando o array de contadores com o tamanho
* sendo o máximo inteiro presente no array a ser ordenado.
*
* Voce pode assumir que o maior inteiro armazenado não chega a 100.
*
*/
public class CountingSort{
public void sort(int[] array, int leftIndex, int rightIndex) {
if( (leftIndex < rightIndex) && (array.length) > 1 && (validIndexes(array, leftIndex,rightIndex)) ) {
int k = findHighestValue(array, leftIndex, rightIndex);
countingSort(array, k , leftIndex, rightIndex);
}
else {
return;
}
}
private int findHighestValue(int[] array, int leftIndex, int rightIndex) {
int k = array[leftIndex];
for(int i = leftIndex + 1; i <= rightIndex; i++) {
if(array[i] > k){
k = array[i];
}
}
return k;
}
private void countingSort(int[] initialArray, int k, int leftIndex, int rightIndex) {
int[] countingArray = new int[k + 1];
Arrays.fill(countingArray, 0);
// frequencia
for(int i = leftIndex; i <= rightIndex; i++) {
countingArray[initialArray[i]] += 1;
}
// cumulativa
for(int i = 0; i < countingArray.length - 1; i++) {
countingArray[i+1] += countingArray[i];
}
int[] orderedArray = new int[rightIndex - leftIndex + 1];
for(int i = rightIndex; i >= leftIndex; i--){
countingArray[initialArray[i]] -= 1;
orderedArray[countingArray[initialArray[i]]] = initialArray[i];
}
for(int i = leftIndex; i <= rightIndex; i++){
initialArray[i] = orderedArray[i-leftIndex];
}
}
private boolean validIndexes(int[] array, int leftIndex, int rightIndex) {
boolean result = true;
if( leftIndex >= array.length || leftIndex > rightIndex || leftIndex < 0) {
result = false;
}
else if(rightIndex >= array.length || rightIndex < 0) {
result = false;
}
return result;
}
}