常见排序算法的js实现

Posted by Xiaosa's Blog on March 15, 2020

快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function jsQuickSort(array) {
    if (array.length <= 1) {
        return array;
    }
    const pivotIndex = Math.floor(array.length / 2);
    const pivot = array.splice(pivotIndex, 1)[0];  //从数组中取出我们的"基准"元素
    const left = [], right = [];
    array.forEach(item => {
        if (item < pivot) {  //left 存放比 pivot 小的元素
            left.push(item); 
        } else {  //right 存放大于或等于 pivot 的元素
            right.push(item);
        }
    });
    //至此,我们将数组分成了left和right两个部分
    return jsQuickSort(left).concat(pivot, jsQuickSort(right));  //分而治之
}

const arr = [98, 42, 25, 54, 15, 3, 25, 72, 41, 10, 121];
console.log(jsQuickSort(arr));  //输出:[ 3, 10, 15, 25, 25, 41, 42, 54, 72, 98, 121 ]

选择排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

function selectSort(arr) {
    let min
    for (let outer = 0; outer < arr.length - 2; ++outer) {
        min = outer
        for (let inner = outer + 1; inner <= arr.length - 1; ++inner) {
            arr[inner] < arr[min] && (min = inner)
        }
            swap(arr,outer,min)
    }
    return arr
}


function swap(arr,index1,index2) {
    const backup = arr[index1]
    arr[index1] = arr[index2]
    arr[index2] = backup
}


function benchMark(fun) {
    if(typeof fun !== 'function') {
        console.warn('benchMark should receive a function');
    }
    console.time('test')
    let res = fun()
    console.timeEnd('test')
    console.log('排序结果:',res);
}

benchMark(()=>selectSort([12,123,435,765,324,5,76,32]))