Selection Sort (JavaScript) - Spot the mistake please?

I can’t understand why the following code doesn’t sort the input array. Can someone help please? I managed to make it work by setting the min at each iteration to the index value (var min = i ) rather than the element value (var min = array[i]) but I cannot find the reason why this particular approach isn’t working. Will be grateful for any help.

function selectionSort(array) {

  // change code below this line

  for(var i = 0; i < array.length; i++){

    var min = array[i];

    for(var j = i+1; j < array.length; j++){

      if(array[j] < min){

        min = array[j];

      }

    }

    

    var temp = array[i];

    array[i] = min;

    array[array.indexOf(min)] = temp;

  }

  return array;

  // change code above this line

}

console.log(selectionSort([5,2,6,1,10]));

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Since you’re modifying the array in place, you can’t use indexOf() because you may have repeated values and indexOf() returns the index of the first one that matches. Your code has this problem too because line 2 assigns the minimum at either the same position it was originally or nearer to the front of the array and indexOf() in line 3 finds the instance you just inserted in line 2, not necessarily the one you want to replace with temp later in the array.

However, your instincts are correct in that you need to track the index of the minimum value you are moving.

Thanks a lot. Got it figured out.