fork download
  1. import java.util.Scanner;
  2. import java.util.Arrays;
  3.  
  4. public class Main {
  5.  
  6. static int getMax(int[] arr, int n) {
  7. int maxVal = arr[0];
  8. for (int i = 1; i < n; i++) {
  9. if (arr[i] > maxVal) {
  10. maxVal = arr[i];
  11. }
  12. }
  13. return maxVal;
  14. }
  15.  
  16. public static void countingSort(int[] arr, int n, int exp) {
  17. int[] output = new int[n];
  18. int[] count = new int[10];
  19.  
  20. Arrays.fill(count, 0);
  21.  
  22. for (int i = 0; i < n; i++) {
  23. count[(arr[i] / exp) % 10]++;
  24. }
  25.  
  26. for (int i = 1; i < 10; i++) {
  27. count[i] += count[i - 1];
  28. }
  29.  
  30. for (int i = n - 1; i >= 0; i--) {
  31. output[count[(arr[i] / exp) % 10] - 1] = arr[i];
  32. count[(arr[i] / exp) % 10]--;
  33. }
  34.  
  35. for (int i = 0; i < n; i++) {
  36. arr[i] = output[i];
  37. }
  38. }
  39.  
  40. public static void radixSort(int[] arr, int n) {
  41. int maxVal = getMax(arr, n);
  42.  
  43. for (int exp = 1; maxVal / exp > 0; exp *= 10) {
  44. countingSort(arr, n, exp);
  45. }
  46. }
  47.  
  48. public static void main(String[] args) {
  49. Scanner scanner = new Scanner(System.in);
  50. System.out.print("Enter the number of elements (n): ");
  51. if (!scanner.hasNextInt()) {
  52. System.out.println("Invalid input for array size.");
  53. scanner.close();
  54. return;
  55. }
  56. int n = scanner.nextInt();
  57.  
  58. if (n <= 0) {
  59. System.out.println("Array size must be positive.");
  60. scanner.close();
  61. return;
  62. }
  63.  
  64. int[] arr = new int[n];
  65.  
  66. System.out.println("Enter " + n + " non-negative integers:");
  67. for (int i = 0; i < n; i++) {
  68. if (!scanner.hasNextInt()) {
  69. System.out.println("Fewer than " + n + " integers provided. Stopping.");
  70. scanner.close();
  71. return;
  72. }
  73. arr[i] = scanner.nextInt();
  74. }
  75. scanner.close();
  76.  
  77. radixSort(arr, n);
  78.  
  79. System.out.print("Sorted Array: ");
  80. for (int i = 0; i < n; i++) {
  81. System.out.print(arr[i] + " ");
  82. }
  83. System.out.println();
  84. }
  85. }
Success #stdin #stdout 0.17s 60816KB
stdin
5
8 7 5 2 1
stdout
Enter the number of elements (n): Enter 5 non-negative integers:
Sorted Array: 1 2 5 7 8