Skip to content

Instantly share code, notes, and snippets.

@aalvarado
Last active August 22, 2018 16:48
Show Gist options
  • Save aalvarado/17470755b2b7a92e379214a0b885ded7 to your computer and use it in GitHub Desktop.
Save aalvarado/17470755b2b7a92e379214a0b885ded7 to your computer and use it in GitHub Desktop.
Algorithms
// node -i -e "var heap = require('./heap-min').heap()"
exports.heap = function() {
var items = [];
var root = function() {
return items[0];
};
var addNode = function(e) {
return items.push(e);
}
return {
root: root,
addNode: addNode
}
}
// pick a pivot (last element)
// draw a wall, lowest index
// left most element (current element)
// iterate and put all elements smaller than the pivot
// to the left of the wall
//
// and all elements larger than the pivot to the right of the wall
//
// then drop the pivot in between the wall, so that
// all numbers larger than it and smaller than it are in the
// right half
//
// to swap, if the element is less than the pivot,
// switch the element next to the wall then increment
// wall
function quickSort(list, left, right) {
if (typeof left === 'undefined') left = 0;
if (typeof right === 'undefined') right = list.length - 1;
if (left >= right) return list;
var current = left;
var wall = left;
for(current; current < right ; current++) {
if (list[current] <= list[right]) {
swap(list, current, wall);
wall++;
}
}
swap(list, wall, right)
quickSort(list, left, wall - 1);
quickSort(list, wall, right);
return list;
}
function swap(list, indexA, indexB) {
var temp = list[indexA]
list[indexA] = list[indexB];
list[indexB] = temp;
}
const arguments = process.argv.slice(2).map(function (e){
return parseInt(e, 10);
})
const res = quickSort(arguments);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment