Created
October 3, 2018 23:20
-
-
Save maurobaraldi/6b0efb3ede814ba73cf2567f89426f57 to your computer and use it in GitHub Desktop.
Count Sort Java Implementation
This file contains hidden or 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
public class SortingAlgorithms { | |
public void count_sort(int arr[]) { | |
int n = arr.length; | |
// The output character array that will have sorted arr | |
int output[] = new int[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 | |
// To make it stable we are operating in reverse order. | |
for (int i=n-1; i>=0; 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) { | |
SortingAlgorithms sa = new SortingAlgorithms(); | |
int arr[] = {1,0,3,9,2,5,8,4,6,7}; | |
sa.count_sort(arr); | |
System.out.print("Sorted character array is "); | |
for (int i=0; i<arr.length; ++i) { | |
System.out.print(arr[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment