java - 计数排序实现
问题描述
你好我在java中实现计数排序方法有困难。我相信问题来自我在方法中的最后两个循环。我收到一个 ArrayIndexOutOfBounds 异常:8。我相信这来自我倒数第二个 for 循环,当索引 5 处的值为 8 但我不知道如何解决这个问题。任何帮助表示赞赏。谢谢!
在我的代码中,k 是输入数组中的最大值。
代码:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
解决方案
问题出在第一个循环中,因为数组temp
长度为 6,并且您在那里进行了 7 次交互。
所以在for
它试图做temp[6]=0
的最后,你的数组的最后一个位置是temp[5]
.
要解决此问题,请将您的第一个循环更改为:
for (int i = 0; i < k; i++){
在最后一个循环中,您将得到相同的异常原因input[8]
不存在。
推荐阅读
- c# - dotnet core program.cs 行为不同 - 无法创建“AppDbContext”类型的对象
- r - 在 R 中重命名和合并行
- analytics - 使用 Kinesis Analytics 分析事件和相关的缺失事件,及时分开?
- c# - 当类不使用 JSON 字符串提供的所有属性时,将 JSON 字符串转换为类
- java - 列表接口的 add 方法在没有正文时如何工作?list接口的add方法定义在哪里?
- laravel-5 - Laravel Lumen 5.4 中的迁移引发“遇到非数值”错误
- linux - Git 的平均备份时间是多少
- asp.net-mvc - ASP.NET MVC 使用编辑器模板创建对象
- google-cloud-platform - 谷歌物联网与 Xively api 可用性
- c# - 使用 MongoDB 和 C# 新驱动程序版本 (2.0) 更新嵌入式文档属性