编辑代码



let arr = [96, 25, 46, 33, 72, 198, 15, 27, 66]
let arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 冒泡排序
// 双层循环,第一层循环遍历需要比较的对象
// 第二层循环,比较的次数,如最后一次循环只需要比较一次,若比较途中发现数组已有序,跳出循环
function mPSort(arr) {
    for (let i = 0; i < arr.length - 1; i++) {
        let isChange = 0;
        for (let j = 0; j < arr.length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
                isChange = 1
            }
        }
        if (isChange == 0) {
            break;
        }
    }
    return arr
}

//console.log(mPSort(arr))

// 选择排序,找到数组最大值,与数组最后一位元素交换,下次循环的数组长度减1
// 两个for循环,外层循环控制排序的趟数,内层循环找到当前趟数的最大值,随后与当前趟数组最后的一位元素交换

function xZSort(arr) {
    for (let i = 0; i < arr.length - 1; i++) {//9
        let maxIndex = 0
        for (let j = 0; j < arr.length - i; j++) {//8
            if (arr[j] > arr[maxIndex]) {
                maxIndex = j
            }
        }
        [arr[maxIndex], arr[arr.length - i - 1]] = [arr[arr.length - i - 1], arr[maxIndex]]

    }
    return arr
}

// console.log(xZSort(arr))

// 插入排序,将每一项插入当前最符合的位置

function cRSort(arr) {
    let result = []
    for (let i = 0; i < arr.length; i++) {
        let index = 0;
        for (let j = 0; j < result.length; j++) {
            if (result[j] < arr[i]) {
                index = j + 1
            }
        }
        result.splice(index, 0, arr[i])
    }
    return result

}

//console.log(cRSort(arr))


function kSSort(arr){
    if(arr.length<2){
        return arr
    }else{
        const xxx = arr[0]
        const left = []
        const center = []
        const right = []
        arr.forEach(current=>{
            if(current<xxx){ left.push(current)}
            else if(current>xxx) {right.push(current)}
            else {center.push(current)}
        })

        console.log('left',left)
        console.log('center',center)
        console.log('right',right)
         console.log('----------------------------------------')

        return kSSort(left).concat(center).concat(kSSort(right))
    }
}

console.log(kSSort(arr))