排序算法

冒泡排序

    function bubbleSort(array) {
        let length = array.length;
        for (let i = 0; i < length; i++) {
            for (let j = 0; j < length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    let temp = array[j + 1];
                    array[j + 1] = array[j];
                    array[j] = temp;
                }
            }
        }
        return array;
    }

选择排序

function selectSort(array) {
        let length = array.length;
        let postion = 0;
        let temp;
        for (let i = 0; i < length; i++) {
            postion = i;
            for (let j = i; j < length; j++) {
                if (array[j] > array[postion]) {
                    postion = j;
                }
            }
            if (i !== postion) {
                temp = array[i];
                array[i] = array[postion];
                array[postion] = temp;
            }
        }
        return array;
    }

插入排序

    function insertionSort(array) {
        let length = array.length;
        for (let i = 1; i < length; i++) {
            let temp = array[i];
            let j = i;
            for (let k = i - 1; k >= 0; k--) {
                if (array[k] < temp) {
                    array[k + 1] = array[k];
                    j = k;
                }
            }
            array[j] = temp;
        }
    }
    function insertionSort(array) {
        let length = array.length;
        for (let i = 1; i < length; i++) {
            let temp = array[i];
            let j = i;
            while (j > 0 && array[j - 1] < temp) {
                array[j] = array[j - 1];
                j--;
            }
            array[j] = temp;
            console.log(array);
        }
    }

归并排序

    function mergeSort(items) {
        if (items.length === 1) {
            return items;
        }
        let middle = Math.floor(items.length / 2);
        let left = items.slice(0, middle);
        let right = items.slice(middle);
        return merge(mergeSort(left), mergeSort(right));
    }

    function merge(left, right) {
        let result = [];
        let il = 0;
        let ir = 0;

        while (il < left.length && ir < right.length) {
            if (left[il] < right[ir]) {
                result.push(left[il++]);
            } else {
                result.push(right[ir++]);
            }
        }
        while (il < left.length) {
            result.push(left[il++]);
        }
        while (ir < right.length) {
            result.push(right[ir++]);
        }
        return result;
    }

转载于:https://my.oschina.net/jasper1987/blog/1840025

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值