Skip to content

Instantly share code, notes, and snippets.

@alexcambose
Created January 12, 2019 13:37
Show Gist options
  • Save alexcambose/6aee42f7d919db62f92dad334221773a to your computer and use it in GitHub Desktop.
Save alexcambose/6aee42f7d919db62f92dad334221773a to your computer and use it in GitHub Desktop.
JavaScript Selection Sort
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