forked from srbcheema1/Algo_Ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
srbcheema1#20. Added and implemented counting sort with java.
- Loading branch information
1 parent
e9afc43
commit 19517fb
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
public class CountingSort | ||
{ | ||
public static void sort(char arr[]) | ||
{ | ||
int n = arr.length; | ||
|
||
// The output character array that will have sorted arr | ||
char output[] = new char[n]; | ||
|
||
// Create a count array to store count of inidividul | ||
// characters and initialize count array as 0 | ||
int count[] = new int[256]; | ||
for (int i = 0; i < 256; ++i) | ||
count[i] = 0; | ||
|
||
// store count of each character | ||
for (int i=0; i<n; ++i) | ||
++count[arr[i]]; | ||
|
||
// Change count[i] so that count[i] now contains actual | ||
// position of this character in output array | ||
for (int i = 1; i <= 255; ++i) | ||
count[i] += count[i-1]; | ||
|
||
// Build the output character array | ||
for (int i = 0; i < n; ++i) | ||
{ | ||
output[count[arr[i]] - 1] = arr[i]; | ||
--count[arr[i]]; | ||
} | ||
|
||
// Copy the output array to arr, so that arr now | ||
// contains sorted characters | ||
for (int i = 0; i<n; ++i) | ||
arr[i] = output[i]; | ||
} | ||
|
||
public static void main(String args[]) | ||
{ | ||
char arr[] = {'h','a','c','k','t','o','b','e','r','f','e','s','t'}; | ||
|
||
sort(arr); | ||
System.out.print("Sorted character array is "); | ||
for (int i=0; i<arr.length; ++i) | ||
System.out.print(arr[i]); | ||
} | ||
} |