nurzain-pradana

CountingSortJava

Nov 8th, 2025 (edited)
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. public class CountingSort {
  2. void sort(char arr[]) {
  3. int n = arr.length;
  4.  
  5. char output[] = new char[n];
  6. int count[] = new int[256];
  7.  
  8. for(int i = 0; i < 256; ++i)
  9. count[i] = 0;
  10.  
  11. for(int i = 0; i < n; ++i)
  12. ++count[arr[i]];
  13.  
  14. for(int i = 1; i <= 255 ; ++i)
  15. count[i] += count[i - 1];
  16.  
  17. for(int i = 0; i < n; ++i)
  18. {
  19. output[count[arr[i]] - 1] = arr[i];
  20. --count[arr[i]];
  21. }
  22.  
  23. for(int i = 0; i < n; ++i)
  24. arr[i] = output[i];
  25.  
  26. }
  27.  
  28. public static void main(String args[]){
  29. CountingSort ob = new CountingSort();
  30.  
  31. char arr[] = {'g','e','e','k','s','f','o','r','g','e','e','k','s'};
  32.  
  33. ob.sort(arr);
  34.  
  35. System.out.print("Sorted character array is ");
  36. for(int i = 0; i < arr.length; ++i)
  37. System.out.print(arr[i]);
  38.  
  39.  
  40. }
  41.  
  42.  
  43.  
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment