Reputation: 1
I was asked to make a selection sort algorithm, but it's not working and I don't know why. Here's the code:
int count = 0;
int count2;
int min;
int size = scan.nextInt();
int temp = 0;
int[] numbers = new int[size];
while (count < size) {
numbers[count] = scan.nextInt();
count ++;
}
count = 0;
while (count < size) {
count2 = size;
min = numbers[count];
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) {
min = count2;
}
}
temp = numbers[temp];
numbers[temp] = numbers[count];
numbers[count] = temp;
count ++;
}
count = 0;
while (count < size) {
System.out.println(numbers[count]);
count ++;
}
}
Input: 10 1 0 2 9 3 8 4 7 5 6
Output: 1 2 9 8 3 3 8 4 7 4
Upvotes: 0
Views: 443
Reputation: 2639
Here is an algorithm that works and make use of a great functionality of for in java. To go through an array or a list you can do for (int current : array)
This is far more convinient than using while or for like you do.
int min;
int mem = 0;
int size = 11;
int [] numbers = {10, 1, 0, 2, 9, 3, 8, 4, 7, 5, 6};
for (int i=0; i<size-1; i++){
min =i;
for(int j=i+1; j<size; j++){
if (numbers[j]<numbers[min]){
min = j;
}
}
// swap
mem= numbers[i];
numbers[i] = numbers[min];
numbers[min] = mem;
}
for (int toPrint : numbers){
System.out.println(toPrint);
}
}
Upvotes: 0
Reputation: 4917
In while loop you try to use numbers[0] element as the index of numbers[] numbers[min]
min = numbers[count]; \\min is value of first element of numbers[]
while (count < count2) {
count2 --;
if (numbers[count2] < numbers[min]) { \\ you try to use value of numbers[0] element as index of numbers[] aray.
min = count2;
}
replace if (numbers[count2] < numbers[min])
with if (numbers[count2] < min)
Upvotes: 1
Reputation: 55609
The fact that you're getting duplicate values in your output (that aren't in your input) means that your swap doesn't work, thus:
temp = numbers[temp];
numbers[temp] = numbers[count];
numbers[count] = temp;
is wrong.
It should be min
, not temp
:
temp = numbers[min];
numbers[min] = numbers[count];
numbers[count] = temp;
Upvotes: 0
Reputation: 7812
temp = numbers[temp];
numbers[temp] = numbers[count];
numbers[count] = temp;
count ++;
Take a second look at this code.
If you ran this where the first input was 11, it would error with index out of range.
In particular, what do you plan to accomplish with temp = numbers[temp]
? You're assigning temp to essentially an arbitrary number, because numbers[0]
could be anything.
Upvotes: 0