Skip to content

Added and Implemented Counting sort with Java. #96. #155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 25, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Sorts/CountSort.java
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]);
}
}