|
| 1 | +package src.main.java.com.sorts; |
| 2 | + |
| 3 | +public class CountingSort { |
| 4 | + |
| 5 | + /** |
| 6 | + * This method sorts the array using counting sort technique |
| 7 | + * |
| 8 | + * @param arr The array to be sorted |
| 9 | + * @return arr Sorted array |
| 10 | + */ |
| 11 | + public Integer[] sort(Integer[] arr) { |
| 12 | + |
| 13 | + // Finding the maximum element in the array |
| 14 | + int max = arr[0]; |
| 15 | + for (int i = 1; i < arr.length; i++) { |
| 16 | + max = Math.max(max, arr[i]); |
| 17 | + } |
| 18 | + |
| 19 | + // Creating the count array - This method will store the count of each element in the unsorted array |
| 20 | + int[] count = new int[max + 1]; |
| 21 | + |
| 22 | + // This loop will store the count of each element in the array |
| 23 | + for (int i = 0; i < max; i++) { |
| 24 | + |
| 25 | + count[arr[i]]++; |
| 26 | + } |
| 27 | + |
| 28 | + // This loop will replace the ith index of the count array with the sum of values at the ith and (i-1) index |
| 29 | + for (int i = 1; i < count.length; i++) { |
| 30 | + |
| 31 | + count[i] = count[i] + count[i - 1]; |
| 32 | + } |
| 33 | + |
| 34 | + // This array will store the sorted array |
| 35 | + Integer[] places = new Integer[arr.length]; |
| 36 | + |
| 37 | + // This loop will put the ith element at is correct position in the places array |
| 38 | + for (int i = 0; i < places.length; i++) { |
| 39 | + |
| 40 | + // Getting the value of the index - the value at the oount array index will be replaced by the value |
| 41 | + // in the original array |
| 42 | + int index = arr[i]; |
| 43 | + places[count[index] - 1] = index; |
| 44 | + count[index]--; |
| 45 | + } |
| 46 | + |
| 47 | + // Copy the places array back to the original array - which will be sorted |
| 48 | + System.arraycopy(places, 0, arr, 0, arr.length); |
| 49 | + |
| 50 | + return arr; |
| 51 | + } |
| 52 | +} |
0 commit comments