JS算法:关于冒泡排序和快排

冒泡排序

比较所有相邻元素,如果第一个比第二个大,则交换它们。执行n-1轮,则完成排序。

Array.prototype.bubbleSort = function() {
    for(let i = 0; i < this.length - 1; i++){
        for(let j = 0; j < this.length - 1 - i; j++){
            if(this[j] > this[j+1]){
                const temp = this[j]
                this[j] = this[j+1]
                this[j+1] = temp 
            }
            // console.log(this);
        }
        console.log(this);
    }
}
const arr = [25, 84, 21, 47, 15, 27, 68, 35, 20];
arr.bubbleSort();

快速排序

定基准:从数组中任意选择一个基准(可以是第一个元素);
分区:所有比基准小的元素放在基准前面,比基准大的元素放在基准后面,形成左右两个分区;
递归:递归地对基准前后的数组进行分区。

Array.prototype.quickSort = function(arr){
    const res = (arr) => {
        if(arr.length <= 1){
            return arr;
        }
        const left = [];
        const right = [];
        const mid = arr[0];
        for(let i = 1; i < arr.length; i++){
            if(arr[i] <= mid){
                left.push(arr[i]);
            }else{
                right.push(arr[i]);
            }
        }

        return [...res(left), mid, ...res(right)]
    }
    console.log(this);
    const result = res(this);
    console.log(result);
    result.forEach((item, i) => {
        this[i] = item
    })
    console.log(this);
}
const arr = [25, 84, 21, 47, 15, 27, 68, 35, 20];
arr.quickSort();

算法的动画效果可以在此处观看Visualgo.net

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值