How to Make Quick Sort - 快速排序法 演算法中較為普及的
function quickSort(arr) {
if(arr.length<=1) {return arr;}
console.log(arr);
let left = [],
right = [],
mid = arr.splice(0,1)[0];
console.log(arr);
for(let i in arr) {
if(arr[i]<=mid){ left.push(arr[i]);}
else if(arr[i]>mid){ right.push(arr[i]);}
}
return quickSort(left).concat(mid, quickSort(right));
};
console.log(quickSort([9,8,8,4,5,1,2,11]));
// const arrayTest = quickSort([1, 1, 2, 2, 5, 5, 64, 3, 11, 33, 55, 88, 22]);
// console.log(arrayTest.length);
const test = [9, 8, 7, 6, 5, 4, 1, 2, 3, 5];
const answer = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9];
const assert = require('assert');
describe('#quickSort()', () => {
it('should sort for array with complete reverse order', () => {
assert.deepEqual([1,2,3,4,5], quickSort([5,4,3,2,1]));
});
it('should sort for an array with length 1', () => {
assert.deepEqual([1], quickSort([1]));
});
it('should sort for an array with multiple equal values', () => {
assert.deepEqual([3,3,3,5,5,7,7,7], quickSort([7,3,7,5,3,3,5,7]));
});
it('test', () => {
assert.deepEqual([1,2,3], quickSort([3,1,2]));
})
});
Published 3 Sep 2017