雖然javaScript有sort方法
但還是來練習寫一下演算法吧
function quickSort(q){
var ql = q.length;
var less = [];
var greater = [];
var pivotList = [];
console.log(ql);
if (ql <= 1){
return q;
} else {
var pivot_pos = Math.floor(ql/2);
var pivot = q[pivot_pos];
for (var i = 0; i < ql; i++){
if (i !== pivot_pos){
if (q[i] <= pivot){
less.push(q[i]);
} else {
greater.push(q[i]);
}
}
}
pivotList.push(pivot);
}
return (quickSort(less).concat(pivotList).concat(quickSort(greater)));
}
console.log(quickSort([8,5,2,9,6,3,7,4,1]));