1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| package sorting;
public class CountingSort { void countingSortNative(int[] nums){ int m = 0; for (int num : nums){ m = Math.max(m, num); }
int[] counter = new int[m+1];
for (int num : nums){ counter[num]++; } int i = 0; for (int num=0; num < m+1; num++){ for (int j = 0; j < counter[num]; j++, i++){ for (int k = 0; k < counter[num]; k++,i++){ nums[i] = num; } } }
}
void cotunringSort(int[] nums){ int m = 0; for (int num : nums) m =Math.max(m,num);
int[] counter = new int[m+1]; for (int num : nums) counter[num]++;
for (int i = 0; i < m; i++) { counter[i+1] += counter[i]; }
int n = nums.length; int[] res = new int[n]; for (int i = n; i >= 0; i--){ int num = nums[i]; res[counter[num]-1] = num; counter[num]--; } for (int i = 0; i < n; i++) { nums[i] = res[i]; } }
}
|