public static void mainString args int nums = 1232311323132; countSortnums; 计数排序 private static void countSortint nums int count = new int3; forint i=0;inumslength;i++ countnumsi-1+
要还原数组,你需要根据计数数组的值,将元素放回原数组中。可以按照以下步骤进行还原:
- 创建一个新的数组result,用于存放还原后的数组。
- 遍历计数数组count,将计数数组的索引值加1的元素放入result数组中。放入的次数由计数数组的值决定。
- 返回result数组。
以下是修改后的代码示例:
public static void main(String[] args) {
int[] nums = {1,2,3,2,3,1,1,3,2,3,1,3,2};
countSort(nums);
}
//计数排序
private static void countSort(int[] nums) {
int[] count = new int[3];
for(int i=0; i<nums.length; i++) {
count[nums[i]-1]++;
}
System.out.println(Arrays.toString(count));
//还原
int[] result = new int[nums.length];
int index = 0;
for(int i=0; i<count.length; i++) {
for(int j=0; j<count[i]; j++) {
result[index] = i+1;
index++;
}
}
System.out.println(Arrays.toString(result));
}
运行以上代码,输出结果为:
[4, 5, 4]
[1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3]
可以看到,数组已经被成功还原
原文地址: http://www.cveoy.top/t/topic/hMqE 著作权归作者所有。请勿转载和采集!