Lesson 9 Challenge 2

by nathanesa

JavaScript

var unsortedList = [11, 25, 12, 22, 64];
var sortedList = [];
var noOfValues = unsortedList.length;
document.write("Here's the unsorted array: " + unsortedList + "<br>");

// Repeat the whole algorithm enough times to move every value.
for (var i = 0; i < noOfValues; i++) {
	
  // Identify the smallest value currently in the unsorted list, AND ITS POSITION!
  var smallest = 100;
  for (var j = 0; j < unsortedList.length; j++) {
    if (unsortedList[j] < smallest) {
      smallest = unsortedList[j];
      var smallestPos = j;
    }
  }
	
  // Move the smallest value across to the sorted list.
  unsortedList.splice(smallestPos, 1);
  sortedList.push(smallest);
  
  // Display as we go.
  document.write("Here's the sorted array: " + sortedList + "<br>");
  
}