Web前端之路让前端飞程序员

JavaScript常见排序算法

2017-07-31  本文已影响86人  07120665a058

排序对比

冒泡排序

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

选择排序

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

直接插入排序

function insertSort(array) {
    let len = array.length;
    let key;
    for (let i = 1; i < len; i++) {
        key = array[i];
        let j = i - 1;
        while (j >= 0 && array[j] > key) {
            array[j + 1] = array[j];
            j--;
        }
        array[j + 1] = key;
    }
    return array;
}
let array = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 4];
console.log(insertSort(array));

快速排序

function quicksort(array) {
    if(array.length<=1){
        return array;
    }
    let index = Math.floor(array.length/2);
    let num = array.splice(index,1);
    let left=[],right=[];
    for(let i = 0;i<array.length;i++){
        if(array[i]<num){
            left.push(array[i]);
        }
        else {
            right.push(array[i]);
        }
    }
    return quicksort(left).concat(num,quicksort(right));
}
let array = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 4];
console.log(quicksort(array));

归并排序(自上而下)

function mergeSort(array) {
    if (array.length < 2) {
        return array;
    }
    let middle = parseInt(array.length / 2);
    let left = array.slice(0, middle);
    let right = array.slice(middle);
    return merge(mergeSort(left), mergeSort(right))
}
function merge(left,right) {
    let result = [];
    while (left.length&&right.length){
        if(left[0]<right[0]){
            result.push(left.shift());
        }
        else{
            result.push(right.shift());
        }
    }
    while (left.length){
        result.push(left.shift());
    }
    while (right.length){
        result.push(right.shift());
    }
    return result;
}
let array = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 4];
console.log(mergeSort(array));

参考文章推荐
十大经典排序算法的 JS 版

上一篇下一篇

猜你喜欢

热点阅读