js实现的快速排序算法

function quickSort(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    var pivotIndex = Math.floor(arr.length / 2),
        left = [],
        right = [],
        pivot = arr.splice(pivotIndex, 1)[0];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] <= pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return quickSort(left).concat([pivot], quickSort(right));
}


var arr = [1, 2, 2, 1, 2, 34,45, 12, 31, 21, 1];
console.log(quickSort(arr))

你可能感兴趣的:(数据结构与算法)