forked from Amigo2k20/java_programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounting Sort.java
More file actions
34 lines (30 loc) · 768 Bytes
/
Counting Sort.java
File metadata and controls
34 lines (30 loc) · 768 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
class Main {
void sort(char arr[])
{
int n = arr.length;
char output[] = new char[n];
int count[] = new int[256];
for (int i = 0; i < 256; ++i)
count[i] = 0;
for (int i = 0; i < n; ++i)
++count[arr[i]];
for (int i = 1; i <= 255; ++i)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
for (int i = 0; i < n; ++i)
arr[i] = output[i];
}
public static void main(String args[])
{
Main ob = new Main();
char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
ob.sort(arr);
System.out.print("Sorted character array is ");
for (int i = 0; i < arr.length; ++i)
System.out.print(arr[i]);
}
}