[英]How to write quick sort on Node.js
I'm continue trying to write a alrorithms on Node.js like on the book Algorithms, 4th ed. 我继续尝试在Node.js上编写算法,如《算法》第4版。 Sedgewick, Wayne. 韦奇塞奇威克。 There all the examples written on Java. 有所有用Java编写的示例。
I have this quick sort module: 我有这个快速排序模块:
"use strict";
const _ = require('lodash');
module.exports = (function () {
function _partition(array, lo, hi) {
let i = lo;
let j = hi + 1;
let v = array[lo];
while (true) {
while (_less(array[++i], v)) {
if (i === hi) {
break;
}
}
while (_less(v, array[--j])) {
if (j === lo) {
break;
}
}
if (i >= j) {
break;
}
_exch(array, i, j);
}
_exch(array, lo, j);
return j;
}
function sort(array) {
_sort(array, 0, array.length - 1);
}
function _sort(array, lo, hi) {
if (hi <= lo) {
return null;
}
let j = _partition(array, lo, hi);
_sort(array, lo, j - 1);
_sort(array, j + 1, hi);
}
function _less(array, i, min) {
return array[i] < array[min];
}
function _exch(array, i, min) {
let temp = array[i];
array[i] = array[min];
array[min] = temp;
}
return {
sort: sort
};
})();
I use mocha and chai for testing with this function: 我使用mocha和chai进行此功能的测试:
function isSorted(array) {
for(let i = 1, size = array.length; i < size; i++) {
if (array[i] < array[i-1]) {
return false;
}
}
return true;
}
and quick sort not working. 快速排序不起作用。 I need the same implementation as in book, but on js. 我需要与书中相同的实现,但在js上。
You can see original implementation here: quick sort in java 您可以在此处看到原始的实现: Java中的快速排序
That implementation is ugly. 该实现是丑陋的。
Sorry, I won't be able to help you answer a course question, but here is the beauty of a functionally recursive version of quicksort. 抱歉,我无法帮助您回答课程问题,但这是quicksort的功能递归版本的优点。 Never, ever, use the above in javascript. 永远不要在javascript中使用以上内容。
In ES6 在ES6中
A functionally recursive quicksort. 功能上递归的快速排序。
const quicksort = ([head, ...tail]) => head === undefined ? [] :
[...quicksort([...tail.filter(a => a <= head)]), head, ...quicksort([...tail.filter(a => a > head)])];
Usage 用法
console.log(quicksort([1,3,1,0,6,8,9,12,15,22,54, 111,12,2,3,4,5,6,7,-1]));
Your function _less
uses indexes as arguments: 您的函数_less
使用索引作为参数:
function _less(array, i, min) {
return array[i] < array[min];
but you call it with array elements values : 但是你用数组元素值来调用它:
let v = array[lo];
while (_less(array[++i], v)
(and omit first argument array
- is it legal in JS?) (并省略第一个参数array
-在JS中合法吗?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.