Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Bruce Illes
6,098 PointsFind index of minimum value in a subarray
As well as using Treehouse as learning source I've been using Khan academy to help give me a better grasp on algorithms. I'm currently stuck on the "Challenge: Find minimum value in the subarray."
Question: 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.
Once implemented, uncomment the Program.assertEqual() at the bottom to verify that the test assertion passes.
My Problem: Is concerning the IF function. I believe I have the formula correct but what the variables should equal when IF is true loses me.
This might be one big brain fart. But I would appreciate any help on this!
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;
// Loop over items starting with startIndex,
// updating minValue and minIndex as needed:
for(var nextIndex = minIndex + 1; nextIndex <array.length ; nextIndex++){
if( nextIndex <= minIndex ){
minIndex= startIndex;
minValue = array[minIndex];
}
}
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);
1 Answer

Hao Tran
17,333 PointsWhat you have currently written is comparing the indexes, rather than the values. The way it's written above, it will never enter the if statement, since you've already stated "nextIndex = minIndex + 1;", and are only incrementing it from there. It should be more like this:
if (array[nextIndex] < minValue) {
minValue = array[nextIndex];
minIndex = nextIndex;
}