Created
January 12, 2019 13:37
-
-
Save alexcambose/6aee42f7d919db62f92dad334221773a to your computer and use it in GitHub Desktop.
JavaScript Selection Sort
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
let array = [3, 1, 4, 5, 3, 2, 6]; | |
for (i = 0; i < array.length - 1; i++) { | |
let nextMinIndex = i; | |
for (j = i + 1; j < array.length; j++) { | |
// search for the smallest number in the unsorted partition | |
if (array[j] < array[nextMinIndex]) nextMinIndex = j; | |
} | |
if (nextMinIndex != i) { | |
// swap | |
let temp = array[i]; | |
array[i] = array[nextMinIndex]; | |
array[nextMinIndex] = temp; | |
} | |
} | |
console.log(array); // [1, 2, 3, 3, 4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment