Last active
July 6, 2016 05:20
-
-
Save minsooshin/3d96c43978403150536eb5359e103843 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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