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 a count sort algorithm.
- Loading branch information
1 parent
545f34d
commit 18f1101
Showing
1 changed file
with
40 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,40 @@ | ||
public class countsort | ||
{ | ||
public static void sort (char arr[]) | ||
{ | ||
int n = arr.length; | ||
|
||
char output[] = new char[n]; | ||
|
||
int count[] = new int[256]; | ||
for (int i = 0; i < n; ++i) | ||
count[i] = 0; | ||
|
||
for (int i = 0 ; i < n; ++i) | ||
++count[arr[i]]; | ||
|
||
for (int i = 1; i <= 255; ++i) | ||
count[1] += count[i - 1]; | ||
|
||
for (int i = 0; i < n; ++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[]) | ||
{ | ||
char arr[] = {'h','a','c','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]); | ||
} | ||
} |