Selection sort an array - Node.js Algorithm

Node.js examples for Algorithm:Sort

Description

Selection sort an array

Demo Code


// SORTING//from   w  w  w. ja v a2  s . c o m
function swap(arr, i, j) {
  var temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}

function selectionSort(arr) {
  var min, minIndex;
  for (var i = 0, len = arr.length; i < len - 1; i++) {
    min = arr[i];
    minIndex = i;
    for (var j = i + 1; j < len; j++) {
      if (arr[j] < min) {
        min = arr[j];
        minIndex = j;
      }
    }
    swap(arr, i, minIndex);
  }
  return arr;
}

Related Tutorials