Mazri_02
Mazri_02

Reputation: 25

Why did my Selection Sort print in the same position as before?

its me again. This time I tried to make a Selection Sort using JavaScript. Everything went well until my code didn't print the specific output that I want. If you tried to run my code below, the second-last index in the array didn't sort properly. Can anyone give me a brief explanation?

Here's the code by the way,

var num = [30,1,90,3,2,34];
var bilnum = num.length,i,j,min;
var temp = 0;

for(i = 0; i < bilnum - 1; i++){
    min = i;
    for(j = i + 1; j < bilnum ; j++){
        if(num[j] < num[min]){
        min = j;
        }
        if(min != i){
            temp = num[i];
            num[i] = num[min];
            num[min] = temp;
        }
    }
}  

document.write(num)

Upvotes: 0

Views: 27

Answers (1)

namar sood
namar sood

Reputation: 1590

You need to move the below snippet from the inner loop to the end of the outer loop as you need to swap after finding the min index.

if(min != i){
            temp = num[i];
            num[i] = num[min];
            num[min] = temp;
        }

So the code will look something like this

var num = [30,1,90,3,2,34];
var bilnum = num.length,i,j,min;
var temp = 0;

for(i = 0; i < bilnum - 1; i++){
    min = i;
    for(j = i + 1; j < bilnum ; j++){
        if(num[j] < num[min]){
        min = j;
        }
        
    }
    if(min != i){
        temp = num[i];
        num[i] = num[min];
        num[min] = temp;
    }
}  

console.log(num);

Upvotes: 1

Related Questions