通过可汗学院的javascript选择排序

时间:2015-06-08 04:39:26

标签: javascript algorithm

我不确定我的代码中出错了什么,但它正确排序了数字,但也留下了这个输出:

Array after sorting: ,,,,,,,7,,9,,11,,,,,,,,,,,22,,,,,,,,,,,,,,,,,,,,42,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,88,,,,,,,,,,,99 

请帮我解决我的代码问题!

var swap = function(array, firstIndex, secondIndex) {
        var temp = array[firstIndex];
        array[firstIndex] = array[secondIndex];
        array[secondIndex] = temp;
    };

var indexOfMinimum = function(array, startIndex) {

    var minValue = array[startIndex];
    var minIndex = startIndex;

    for(var i = minIndex + 1; i < array.length; i++) {
        if(array[i] < minValue) {
            minIndex = i;
            minValue = array[i];
        }
    } 
    return minIndex;
}; 

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

var array = [22, 11, 99, 88, 9, 7, 42];
selectionSort(array);
println("Array after sorting: " + array);

Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);

2 个答案:

答案 0 :(得分:1)

您不希望索引为i的值,您只需要i本身。

var min = indexOfMinimum(array, array[i]);

应该是

var min = indexOfMinimum(array, i);

答案 1 :(得分:0)

var selectionSort = function(array) {

    var length = array.length;

    for(var i = 0; i < length; i++){
        var min = indexOfMinimum(array,i);
        swap(array, i, min);
    }
}