Skip to content

Commit b69548e

Browse files
Merge pull request #155 from achaJackson/master
Added and Implemented Counting sort with Java. #96.
2 parents 6531362 + 35bd2bb commit b69548e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Sorts/CountSort.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
public class CountingSort
2+
{
3+
public static void sort(char arr[])
4+
{
5+
int n = arr.length;
6+
7+
// The output character array that will have sorted arr
8+
char output[] = new char[n];
9+
10+
// Create a count array to store count of inidividul
11+
// characters and initialize count array as 0
12+
int count[] = new int[256];
13+
for (int i = 0; i < 256; ++i)
14+
count[i] = 0;
15+
16+
// store count of each character
17+
for (int i=0; i<n; ++i)
18+
++count[arr[i]];
19+
20+
// Change count[i] so that count[i] now contains actual
21+
// position of this character in output array
22+
for (int i = 1; i <= 255; ++i)
23+
count[i] += count[i-1];
24+
25+
// Build the output character array
26+
for (int i = 0; i < n; ++i)
27+
{
28+
output[count[arr[i]] - 1] = arr[i];
29+
--count[arr[i]];
30+
}
31+
32+
// Copy the output array to arr, so that arr now
33+
// contains sorted characters
34+
for (int i = 0; i<n; ++i)
35+
arr[i] = output[i];
36+
}
37+
38+
public static void main(String args[])
39+
{
40+
char arr[] = {'h','a','c','k','t','o','b','e','r','f','e','s','t'};
41+
42+
sort(arr);
43+
System.out.print("Sorted character array is ");
44+
for (int i=0; i<arr.length; ++i)
45+
System.out.print(arr[i]);
46+
}
47+
}

0 commit comments

Comments
 (0)