Skip to content

Instantly share code, notes, and snippets.

@minsooshin
Last active July 6, 2016 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minsooshin/3d96c43978403150536eb5359e103843 to your computer and use it in GitHub Desktop.
Save minsooshin/3d96c43978403150536eb5359e103843 to your computer and use it in GitHub Desktop.
const swap = (array, a, b) => {
const temp = array[a];
array[a] = array[b];
array[b] = temp;
return array;
};
function selectionSort(array) {
const n = array.length;
// iterate all elements of array except the last element
for (let i = 0; i < n - 1; i++) {
// consider the first element of the unsorted portion
// of the array is a minimum
let min = i;
// iterate each unsorted element
for (let j = i + 1; j < n; j++) {
// compare to current element to the minimum element
// we've seen so far
// if the current element is less than minimum element
if (array[j] < array[min]) {
// remember current element as a new minimum
min = j;
}
}
// swap the minimum element with the first unsorted element
if (min !== i) {
swap(array, min, i);
}
}
return array;
}
console.log(selectionSort([76, 23, 4, 7, 11]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment