Summary of “Arrays”. Part 2
Sorting an array.
var numbers = [12, 3, 7, 9, 10, 5];
for (var i = 0; i <= numbers.length - 2; i++) {
var minValue = numbers[i];
for (var j = i + 1; j <= numbers.length - 1; j++) {
if (numbers[j] < minValue) {
minValue = numbers[j];
var swap = numbers[i];
numbers[i] = minValue;
numbers[j] = swap;
}
}
}
// Logs [3, 5, 7, 9, 10, 12];
console.log(numbers);The array numbers is sorted in ascending order. Each outer-loop iteration starts with the value at index i as minValue. The inner loop compares it with the later elements. Whenever it finds a smaller value, it updates minValue and swaps that value into position i. The temporary variable swap preserves the displaced value. When the outer iteration ends, the smallest remaining value is in position i.
Continue