1.动图演示:
2.代码示例:
package test1;
import java.util.Arrays;
public class Test3 {
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 1, 4, 52, 1, 4};
int[] arr = count_sort(nums, getMax(nums));
for (int i : arr) {
System.out.print(i + " ");
}
}
public static int getMax(int[] nums) {
int max = nums[0];
for (int num : nums) {
if (max < num) {
max = num;
}
}
return max;
}
public static int[] count_sort(int[] nums, int max) {
int[] arr = Arrays.copyOf(nums, nums.length);
int[] bucket = new int[max + 1];
for (int val : arr) {
bucket[val]++;
}
int sortedIndex = 0;
for (int i = 0; i < bucket.length; i++) {
while (bucket[i] > 0) {
arr[sortedIndex++] = i;
bucket[i]--;
}
}
return arr;
}
}