【发布时间】:2017-08-23 14:25:11
【问题描述】:
Array.prototype.quickSort = function () {
let self = this;
let len = self.length;
let pivot_pos;
let result = []
if (len < 2) {
return self
}
pivot_pos = self.partition();
let left = self.splice(0, pivot_pos),
right = self.splice(0);
error --> left.quickSort();
error --> right.quickSort();
console.log(left);
console.log(right);
//right_pivot_pos = right.partition();
return this;
}
Array.prototype.partition = function () {
let arr = this;
let pivot_pos = Math.floor((arr.length-1)/2);
let last_small = arr[0]
let i;
//console.log(`before this[0] ${this[0]} and before this[pivot_pos]
${this[pivot_pos]}`);
[arr[pivot_pos], arr[0]] = [arr[0], arr[pivot_pos]];
//console.log(`this[0] ${this[0]} and this[pivot_pos]
${this[pivot_pos]}`);
for (i=1;i<arr.length; i++) {
if(arr[i]<arr[0]) {
//[this[i], this[num]] = [this[num], this[i]];
let tmp = arr[last_small];
arr[last_small] = arr[i];
arr[i] = tmp;
last_small++;
}
}
[arr[0], arr[last_small-1]] = [arr[last_small-1], arr[0]];
return last_small;
}
let sandbox = [1,2,6,5,4,3,7,9];
console.log(sandbox.quickSort());
我不能调用 left.quickSort();和 right.quickSort(); JavaScript堆内存不足...编写此代码的替代方法是什么?我在 git 上在线浏览了一些,但它与计算运行函数的成本不同。
【问题讨论】:
标签: javascript arrays algorithm sorting ecmascript-6