Last active
July 14, 2019 19:39
-
-
Save mcmxc/bd1ece58c25176208772ed0c602bc302 to your computer and use it in GitHub Desktop.
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
function insert(array, rightIndex, value) { | |
for (var j = rightIndex; j >= 0 && array[j] > value; j--) { | |
array[j + 1] = array[j]; | |
} | |
array[j + 1] = value; | |
} | |
function insertionSort(array) { | |
for (var i = 1; i < array.length; i++) { | |
insert(array, i - 1, array[i]); | |
} | |
} | |
// insertionSort([22, 11, 99, 88, 9, 7, 42]); | |
// -> [7, 9, 11, 22, 42, 88, 99]; |
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 merge(array, p, q, r) {} | |
function mergeSort(array, p, r) { | |
if (r > p) { | |
let q = Math.floor((r + p) / 2); | |
mergeSort(array, p, q); | |
mergeSort(array, q + 1, r); | |
merge(array, p, q, r); | |
} | |
} |
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 swap(array, firstIndex, secondIndex) { | |
let temp = array[firstIndex]; | |
array[firstIndex] = array[secondIndex]; | |
array[secondIndex] = temp; | |
}; | |
function indexOfMinimum(array, startIndex) { | |
let minValue = array[startIndex]; | |
let minIndex = startIndex; | |
for (let i = minIndex + 1; i < array.length; i++) { | |
if (array[i] < minValue) { | |
minIndex = i; | |
minValue = array[i]; | |
} | |
} | |
return minIndex; | |
}; | |
function selectionSort(array) { | |
for (let i = 0; i < array.length; i++) { | |
swap(array, i, indexOfMinimum(array, i)); | |
} | |
return array; | |
}; | |
// selectionSort([22, 11, 99, 88, 9, 7, 42]); | |
// -> [7, 9, 11, 22, 42, 88, 99] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment