|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +class CountingSort { |
| 4 | + void countSort(int array[], int size) { |
| 5 | + int[] output = new int[size + 1]; |
| 6 | + |
| 7 | + // Find the largest element of the array |
| 8 | + int max = array[0]; |
| 9 | + for (int i = 1; i < size; i++) { |
| 10 | + if (array[i] > max) |
| 11 | + max = array[i]; |
| 12 | + } |
| 13 | + int[] count = new int[max + 1]; |
| 14 | + |
| 15 | + // Initialize count array with all zeros. |
| 16 | + for (int i = 0; i < max; ++i) { |
| 17 | + count[i] = 0; |
| 18 | + } |
| 19 | + |
| 20 | + // Store the count of each element |
| 21 | + for (int i = 0; i < size; i++) { |
| 22 | + count[array[i]]++; |
| 23 | + } |
| 24 | + |
| 25 | + // Store the cummulative count of each array |
| 26 | + for (int i = 1; i <= max; i++) { |
| 27 | + count[i] += count[i - 1]; |
| 28 | + } |
| 29 | + |
| 30 | + // Find the index of each element of the original array in count array, and |
| 31 | + // place the elements in output array |
| 32 | + for (int i = size - 1; i >= 0; i--) { |
| 33 | + output[count[array[i]] - 1] = array[i]; |
| 34 | + count[array[i]]--; |
| 35 | + } |
| 36 | + |
| 37 | + // Copy the sorted elements into original array |
| 38 | + for (int i = 0; i < size; i++) { |
| 39 | + array[i] = output[i]; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + // Driver code |
| 44 | + public static void main(String args[]) { |
| 45 | + int[] data = { 2, 1, 2, 3, 1, 2, 4 }; |
| 46 | + int size = data.length; |
| 47 | + CountingSort cs = new CountingSort(); |
| 48 | + cs.countSort(data, size); |
| 49 | + System.out.println("Sorted Array in Ascending Order: "); |
| 50 | + System.out.println(Arrays.toString(data)); |
| 51 | + } |
| 52 | +} |
0 commit comments