|
| 1 | +public class SortingStudentAges { |
| 2 | + |
| 3 | + // Method to perform Counting Sort |
| 4 | + public static void countingSort(int[] ages) { |
| 5 | + int minAge = 10; // Minimum age in the range |
| 6 | + int maxAge = 18; // Maximum age in the range |
| 7 | + int range = maxAge - minAge + 1; // Total possible age values |
| 8 | + |
| 9 | + // Step 1: Create a count array to store frequency of each age |
| 10 | + int[] count = new int[range]; |
| 11 | + |
| 12 | + // Step 2: Count occurrences of each age |
| 13 | + for (int age : ages) { |
| 14 | + count[age - minAge]++; |
| 15 | + } |
| 16 | + |
| 17 | + // Step 3: Compute cumulative frequency |
| 18 | + for (int i = 1; i < range; i++) { |
| 19 | + count[i] += count[i - 1]; |
| 20 | + } |
| 21 | + |
| 22 | + // Step 4: Place elements in their correct position in the output array |
| 23 | + int[] sortedAges = new int[ages.length]; |
| 24 | + for (int i = ages.length - 1; i >= 0; i--) { |
| 25 | + int age = ages[i]; |
| 26 | + int position = count[age - minAge] - 1; |
| 27 | + sortedAges[position] = age; |
| 28 | + count[age - minAge]--; // Decrease count |
| 29 | + } |
| 30 | + |
| 31 | + // Step 5: Copy the sorted values back to the original array |
| 32 | + System.arraycopy(sortedAges, 0, ages, 0, ages.length); |
| 33 | + } |
| 34 | + |
| 35 | + // Main method to test sorting |
| 36 | + public static void main(String[] args) { |
| 37 | + int[] studentAges = {12, 15, 10, 18, 17}; |
| 38 | + |
| 39 | + // Sorting the ages |
| 40 | + countingSort(studentAges); |
| 41 | + |
| 42 | + // Display sorted ages |
| 43 | + System.out.println("Sorted Student Ages:"); |
| 44 | + for (int age : studentAges) { |
| 45 | + System.out.print(age + " "); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments