src/快速排序.js
var quick_sort = function(unsorted) {
if (unsorted.size <= 1)
return unsorted;
var pivot = unsorted.pop();
var less = new Array();
var greater = new Array();
unsorted.forEach(function(element){
if (element > pivot)
less.push(element);
else
greater.push(element);
});
return quick_sort(less) + [pivot] + quick_sort(greater);
};
规范/QuickSort.js
describe("#quick_sort", function() {
it("should sort the unsorted array", function() {
var unsorted = [8, 2, 10, 5, 4, 9, 7, 1, 6, 3];
var sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
expect(quick_sort(unsorted)).toEqual(sorted);
});
});
错误信息
RangeError: Maximum call stack size exceeded
at Array.forEach (native)
at quick_sort (file://localhost/Users/jasonkim/projects/algorithm-everyday/quick_sort/javascript/src/QuickSort.js:9:12)
at quick_sort (file://localhost/Users/jasonkim/projects/algorithm-everyday/quick_sort/javascript/src/QuickSort.js:16:10)
我正在尝试使用 jasminejs 测试快速排序功能。我收到上面的错误。我有上面的终止条件if (unsorted.size <= 1) { return unsorted }
。我不确定为什么它没有终止并进入无限循环。