Skip to content

Instantly share code, notes, and snippets.

@mcmxc
Last active July 14, 2019 19:39
Show Gist options
  • Save mcmxc/bd1ece58c25176208772ed0c602bc302 to your computer and use it in GitHub Desktop.
Save mcmxc/bd1ece58c25176208772ed0c602bc302 to your computer and use it in GitHub Desktop.
Sort
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];
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);
}
}
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