排序算法

冒泡

function bubbleSort(arr) {
    var len = arr.length
    for (var i = 0; i < len; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j + 1]
                arr[j + 1] = arr[j]
                arr[j] = temp
            }
        }
    }
    return arr
}
var arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
console.log(bubbleSort(arr))

快排

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

var arr = [2, 1, 5, 8, 3, 7, 4, 6, 9];
console.log(quickSort(arr)); //[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

posted @ 2021-02-26 18:49  懒懒同学不懒  阅读(28)  评论(0编辑  收藏  举报