Reputation: 179
This algorithm given to us in class:
I am having trouble in my attempts to determine the output when the input is an array A[60,35,81,98,14,47]
.
I wanted to get used to the pseudocode syntax, so I tried to convert this to Java syntax, but the resulting program won't show a result. This is my converted code:
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;
}
}
Upvotes: 0
Views: 324
Reputation: 87
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
.
Upvotes: 1
Reputation: 992
int[] test = {60,35,81,98,14,47};
is never used.
Did you mean to pass test
into countSort
? and also do something with it's result.
While I haven't looked at the algorithm really, there is something else wrong here:
int n = a.length + 1;
for (int i = 0; i < (n - 1);) {
count[i] = 0;
}
This will loop indefinatetly. i
never incerements.
Upvotes: 3