forked from Annex5061/java-algorithms
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounting_Sort.java
More file actions
Latest commit
45 lines (33 loc) · 857 Bytes
/
Copy pathCounting_Sort.java
File metadata and controls
45 lines (33 loc) · 857 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
35
36
37
38
39
40
41
42
43
44
classCountingSort {
voidsort(chararr[])
{
intn = arr.length;
charoutput[] = newchar[n];
intcount[] = newint[256];
for (inti = 0; i < 256; ++i)
count[i] = 0;
// store count of each character
for (inti = 0; i < n; ++i)
++count[arr[i]];
for (inti = 1; i <= 255; ++i)
count[i] += count[i - 1];
// Build the output character array
for (inti = 0; i < n; ++i) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
for (inti = 0; i < n; ++i)
arr[i] = output[i];
}
// Driver method
publicstaticvoidmain(Stringargs[])
{
CountingSortob = newCountingSort();
chararr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
ob.sort(arr);
System.out.print("Sorted character array is ");
for (inti = 0; i < arr.length; ++i)
System.out.print(arr[i]);
}
}