Created
May 29, 2017 05:24
-
-
Save vaidehijoshi/7f02b9b76653ffa3d6beb12f507116ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function selectionSort(numbers) { | |
var length = numbers.length; | |
// Traverse through all the elements in the number array. | |
for(var index = 0; index < length; index++) { | |
// Set the current item to be the smallest/minimum. | |
var smallestNumIndex = index; | |
// Find the minimum element in remaining unsorted array. | |
for(var nextNumIndex = index + 1; nextNumIndex < length; nextNumIndex++) { | |
console.log('comparing ' + numbers[smallestNumIndex] + ' and ' + numbers[nextNumIndex]) | |
// If the next number is smaller than the current number, reassign our reference to the the index of the smallest number | |
if(numbers[nextNumIndex] < numbers[smallestNumIndex]) { | |
smallestNumIndex = nextNumIndex; | |
} | |
} | |
if(smallestNumIndex != index) { | |
var currentNumber = numbers[index]; | |
// If the number we're looking at is the smallest in size, swap it with the first element. | |
console.log('swapping the number ' + numbers[smallestNumIndex] + ' for the number ' + numbers[index]); | |
numbers[index] = numbers[smallestNumIndex]; | |
numbers[smallestNumIndex] = currentNumber; | |
} | |
console.log('numbers currently looks like: ' + numbers); | |
} | |
return numbers; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment