“Arrays” memo. 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

We are using cookies to gather information which will help you use our website most effectively. You can read about this here or disable this feature if you want. By continuing to browse the site, you agree to our use of cookies.