Search code examples
sortingselection-sort

What mistake am I doing in this code for selection sort?


var selectionSort = function(array) {
    var minIndex;
    for(var i = 0;i <array.length;i++){
        minIndex = indexOfMinimum(array,i);}
         swap(array,minIndex,i);
};

where indexOfMinimum is used to find the index of min value for the subarray starting at index i. And swap is a popularly known function.


Solution

  • You've got a problem with curly braces, see minIndex = indexOfMinimum(array,i);}. So basically swap(array,minIndex,i); is executed only once, not in the loop body. Your code with corrected style:

    var selectionSort = function(array) {
        var minIndex;
        for(var i = 0; i < array.length; i++) {
            minIndex = indexOfMinimum(array,i);
        }
        swap(array,minIndex,i);
    };
    

    What you need:

    var selectionSort = function(array) {
        var minIndex;
        for(var i = 0; i < array.length; i++){
            minIndex = indexOfMinimum(array,i);
            swap(array,minIndex,i);
        }
    };