Hey guys in this post, we will discuss the most popular sorting algorithm that is Counting sort in Java language.
Read more:
- Check the Complete Java Tutorials
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
- Check the Spring Boot JdbcTemplate Tutorials
class CountingSort
{
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];
}
// Driver method
public static void main(String args[])
{
CountingSort ob = new CountingSort();
char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's'
};
ob.sort(arr);
System.out.print("Sorted character array is ");
for (int i=0; i<arr.length; ++i)
System.out.print(arr[i]);
}
}
Output:
Sorted character array is eeeefggkkorss
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.