Skip to content

Instantly share code, notes, and snippets.

@kyr0
Created March 24, 2019 09:00
Show Gist options
  • Save kyr0/709e099ffc7352c3def86088e50da4c2 to your computer and use it in GitHub Desktop.
Save kyr0/709e099ffc7352c3def86088e50da4c2 to your computer and use it in GitHub Desktop.
wp-node-quicksort
'use strict';
const quickSort = (arr, dimension, left = 0, right = arr.length - 1) => {
const len = arr.length; let index;
if (len > 1) {
index = partition(arr, dimension, left, right);
if(left < index - 1) quickSort(arr, dimension, left, index - 1);
if(index < right) quickSort(arr, dimension, index, right);
}
return arr;
};
const partition = (arr, dimension, left, right) => {
const middle = Math.floor((right + left) / 2), pivot = arr[middle];
let i=left, j=right;
while(i <= j) {
while(arr[i][dimension] > pivot[dimension]) { i++ }
while(arr[j][dimension] < pivot[dimension]) { j-- }
if(i <= j) { [arr[i], arr[j]] = [arr[j], arr[i]]; i++; j-- }
}
return i;
};
const fs = require('fs');
const startTime = Date.now();
const log = (msg) => setImmediate(() => { process.stdout.write(msg); });
fs.readFile("/dev/stdin", 'utf8', (err, text) => {
const map = {}, unsorted = [], lines = text.split("\n");
for (let i=0; i<lines.length; i++) {
const words = lines[i].split(' ');
for (let j=0; j<words.length; j++) {
if (words[j].length === 0) continue;
if (typeof map[words[j]] === 'undefined') map[words[j]] = 1;
else map[words[j]]++;
}
}
for (let word in map) unsorted.push([word, map[word]]);
const sorted = quickSort(unsorted, 1);
for (let i=0; i<sorted.length; i++) log(`${sorted[i][0]}: ${sorted[i][1]}\n`);
const endTime = Date.now();
log(`Time: ${endTime - startTime}ms Items: ${sorted.length}\n`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment