找到最低值的索引,我的断言失败了

Finding the index of lowest value, my assertion is failing

作业是:

Finish writing the function indexOfMinimum, which takes an array and a number startIndex, and returns the index of the smallest value that occurs with index startIndex or greater. If this smallest value occurs more than once in this range, then return the index of the leftmost occurrence within this range.

这是我完成它的尝试

var indexOfMinimum = function(array, startIndex) {
    // Set initial values for minValue and minIndex,
    // based on the leftmost entry in the subarray:  
    var minValue = array[startIndex];
    var minIndex = startIndex;
    for (var i = minIndex + 1; i < array.length; i++) {
        if (array[i] < array[startIndex]) {
            minIndex = i;
            minValue = array[i];
        }
    }

    // Loop over items starting with startIndex, 
    // updating minValue and minIndex as needed:

    return minIndex;
};

var array = [18, 6, 66, 44, 9, 22, 14];
var index = indexOfMinimum(array, 2);

//  For the test array [18, 6, 66, 44, 9, 22, 14], 
//  the value 9 is the smallest of [..66, 44, 9, 22, 14]
//  Since 9 is at index 4 in the original array, 
//  "index" has value 4
println("The index of the minimum value of the subarray starting at index 2 is " + index + ".");
Program.assertEqual(index, 4);

最后的断言失败了。根据我的逻辑,它 returns 4 索引,但我认为它不能正常工作。为什么不呢?

比较

if(array[i]<array[startIndex])

错了。你应该比较

if(array[i]<minValue)

...因为您想知道 array[i] 是否小于您目前找到的最小值,而不是小于您查看的第一个值。

有了这个改变,它起作用了:

var indexOfMinimum = function(array, startIndex) {
// Set initial values for minValue and minIndex,
// based on the leftmost entry in the subarray:  
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];
    }
}

// Loop over items starting with startIndex, 
// updating minValue and minIndex as needed:

return minIndex;
}; 

var array = [18, 6, 66, 44, 9, 22, 14];   
var index = indexOfMinimum(array, 2);

//  For the test array [18, 6, 66, 44, 9, 22, 14], 
//  the value 9 is the smallest of [..66, 44, 9, 22, 14]
//  Since 9 is at index 4 in the original array, 
//  "index" has value 4
console.log("The index of the minimum value of the subarray starting at index 2 is " + index + "."  );


(空间不是邪恶的,顺便说一下。)