- script.js
JavaScript
var usersByDay = [4, 2, 1, 3];
console.log(usersByDay);
// Start loop here
// Sorting from the first element
var currentIndex = 0;
var minValue = usersByDay[currentIndex];
for (var j = currentIndex + 1; j <= usersByDay.length - 1; j++) {
if (usersByDay[j] < minValue) {
minValue = usersByDay[j];
var swap = usersByDay[currentIndex];
usersByDay[currentIndex] = minValue;
usersByDay[j] = swap;
console.log('Swapping ' + swap + ' and ' + minValue);
console.log('Current array: ' + usersByDay);
}
}
console.log('Minimum element ' + minValue + ' is on ' + currentIndex + 'position');
// Complete loop here
// Sorting from the second element
console.log(usersByDay);
currentIndex = 1;
minValue = usersByDay[currentIndex];
for (var j = currentIndex + 1; j <= usersByDay.length - 1; j++) {
if (usersByDay[j] < minValue) {
minValue = usersByDay[j];
var swap = usersByDay[currentIndex];
usersByDay[currentIndex] = minValue;
usersByDay[j] = swap;
console.log('Swapping ' + swap + ' and ' + minValue);
console.log('Current array: ' + usersByDay);
}
}
console.log('Minimum element ' + minValue + ' is on ' + currentIndex + 'position');
// Sorting from the third element
console.log(usersByDay);
currentIndex = 2;
minValue = usersByDay[currentIndex];
for (var j = currentIndex + 1; j <= usersByDay.length - 1; j++) {
if (usersByDay[j] < minValue) {
minValue = usersByDay[j];
var swap = usersByDay[currentIndex];
usersByDay[currentIndex] = minValue;
usersByDay[j] = swap;
console.log('Swapping ' + swap + ' and ' + minValue);
console.log('Current array: ' + usersByDay);
}
}
console.log('Minimum element ' + minValue + ' is on ' + currentIndex + 'position');
Result
Goalscompleted
- Remove the entire code for sorting from the second and third elements.
- Then wrap the entire the code after the second line in a loop that increases the variable
currentIndex
from zero tousersByDay.length - 2
inclusively. Value ofcurrentIndex
must increase by one after each iteration. - Inside this loop, remove the duplicate declaration of the variable
currentIndex
.
Comments