这个算法在课堂上给我们:
当输入是数组A[60,35,81,98,14,47]
时,我在尝试确定输出时遇到了问题。
我想习惯伪代码语法,所以我尝试将其转换为Java语法,但生成的程序不会显示结果。这是我转换的代码:
public class Driver
{
public static void main(String[] args)
{
int[] test = {60, 35, 81, 98, 14, 47};
int[] converse = new int[6];
converse = countSort(test);
for(int i : converse)
{
System.out.println(converse[i]);
}
}
public static int[] countSort(int[] a)
{
int[] s = new int[6];
int[] count = new int[6];
int n = a.length + 1;
for(int i = 0; i < (n-1);)
{
count[i] = 0;
}
for(int i = 0; i < (n-2);)
{
for(int j = (i+1); i < (n-1);)
{
if(a[i] < a[j])
{
count[j] = count[j]+1;//What
}
else
{
count[i] = count[i]+1;
}
}
}
for (int i = 0; i < (n-1);)
{
s[count[i]] = a[i];
}
return s;
}
}
答案 0 :(得分:3)
int[] test = {60,35,81,98,14,47};
从未使用过。
您的意思是将test
传递给countSort
吗?并且也对它的结果做了一些事情。
虽然我没有真正看过算法,但这里还有其他问题:
int n = a.length + 1;
for (int i = 0; i < (n - 1);) {
count[i] = 0;
}
这将无限循环。 i
永远不会有任何影响。
答案 1 :(得分:1)
test
is never used.i
never gets incremented. It will loop infinetely.n = a.length+1;
just use n = a.length
. it makes your code easier to read. You then also have to check all your loops.When you are running the code with a testset larger or less than 6 integer values your code wont run correctly or even fail with an ArrayOutOfBounds Exception, as you allocate the arrays s
and count
for only 6 values.
Try int[] count = new int[a.length];
instead of int[] count = new int[a.length];
. The same for s
.