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);
An array with numbers numbers
is sorted by ascending elements. At each iteration, we compare minValue
with the rest of the array elements. If any of them is less than minValue
, it will be written to minValue
, overwriting the old value, and moved to the beginning of the array. Variable swap
is an auxiliary variable that we can use to swap elements.
Continue