JavaScript算法(三)

系列文章目录

JavaScript算法(一)

JavaScript算法(二)


目录

系列文章目录

前言

11.排序和搜索

冒泡排序

选择排序

插入排序

归并排序

快速排序

顺序搜索

二分搜索

总结


前言

JavaScript算法,排序、搜索。


11.排序和搜索

  • 排序:把某个乱序的数组变成升序或者降序的数组(js排序:数组 sort 方法)
  • 搜索:找出数组中某个元素的下标(js搜索:数组 indexOf 方法)

排序算法:冒泡排序、选择排序、插入排序、归并排序、快速排序...

搜索算法:顺序搜索、二分搜索...

冒泡排序

  • 比较所有相邻元素,如果第一个比第二个大,则交换它们
  • 一轮下来,可以保证最后一个数是最大的
  • 执行 n-1 轮,就可以完成排序
// 冒泡排序时间复杂度:O(n^2)
Array.prototype.bubbleSort = function(){
    for(let i = 0;i < this.length -1;i += 1){
        for(let j = 0;j < this.length - 1 - i;j += 1){
            if(this[j] > this[j+1]){
                const temp = this[j];
                this[j] = this[j + 1];
                this[j+1] = temp;
            }
        }
    }
}

const arr = [5,4,3,2,1];
arr.bubbleSort();

选择排序

  • 找到数组中的最小值,选中它并将其放置在第一位
  • 接着找到第二小的值,选中它并将其放置在第二位
  • 以此类推,执行 n-1 轮
// 选择排序时间复杂度:O(n^2)
Array.prototype.selectionSort = function(){
    for(let i = 0;i < this.length -1;i += 1){
        let indexMin = i;
        for(let j = i;j < this.length;j += 1){
            if(this[j] < this[indexMin]){
                indexMin = j;
            }
        }
        if(indexMin !== i){
            const temp = this[i];
            this[i] = this[indexMin];
            this[indexMin] = temp;
        }
    }
}

const arr = [5,4,3,2,1];
arr.selectionSort();

插入排序

  • 从第二个数开始往前比
  • 比它大就往后排
  • 以此类推进行到最后一个数
// 插入排序时间复杂度:O(n^2)
Array.prototype.insertionSort = function(){
    for(let i = 1;i < this.length;i += 1){
        const temp = this[i];
        let j = i;
        while(j > 0){
            if(this[j-1] > temp){
                this[j] = this[j-1]
            }else{
                break;
            }
            j-=1;
        }
        this[j] = temp;
    }
}

const arr = [2,4,3,5,1];
arr.insertionSort();

归并排序

  • 分:把数组劈成两半,再递归地对子数组进行‘分’操作,直到分成一个个单独的数
  • 合:把两个数合并为有序数组,再对有序数组进行合并,直到全部子数组合并为一个完整的数组

合并两个有序数组

  • 新建一个空数组res,用于存放最终排序后的数组
  • 比较两个有序数组的头部,较小者出队并推入res中
  • 如果两个数组还有值,就重复第二步
// 分 时间复杂度: O(logN) 
// 合 时间复杂度: O(n)
// 时间复杂度: O(n*logN)
Array.prototype.mergeSort = function(){
    const rec = (arr) => {
        if(arr.length === 1) return arr;
        const mid = Math.floor(arr.length / 2);
        const left = arr.slice(0,mid);
        const right = arr.slice(mid,arr.length);
        const orderLeft = rec(left);
        const orderRight = rec(right);
        const res = [];
        while(orderLeft.length || orderRight.length){
            if(orderLeft.length && orderRight.length){
                res.push(orderLeft[0] < orderRight[0]?orderLeft.shift():orderRight.shift())
            }else if(orderLeft.length){
                res.push(orderLeft.shift());
            }else if(orderRight.length){
                res.push(orderRight.shift());
            }
        }
        return res;
    }
    const res = rec(this);
    res.forEach((n,i)=>{ this[i] = n; });
}

const arr = [2,4,3,5,1];
arr.mergeSort();

快速排序

  • 分区:从数组中任意选择一个“基准”,所有比基准小的元素放在基准前面,比基准大的元素放在基准的后面
  • 递归:递归的对基准前后的子数组进行分区
// 递归时间复杂度 O(logN)
// 分区时间复杂度 O(n)
// 时间复杂度 O(n*logN)
Array.prototype.quickSort = function(){
    const rec = (arr) => {
        if(arr.length === 1) return arr;
        const left = [];
        const right = [];
        const md = arr[0];
        for(let i = 1; i < arr.length;i++){
            if(arr[I] < mid){
                left.push(arr[i]);
            }else{
                right.push(arr[i])
            }
        }
        return [...rec(left),mid,...rec(right)]

    }
    const res = rec(this);
    res.forEach((n,i)=>{ this[i] = n; });
}

const arr = [2,4,3,5,1];
arr.quickSort();

顺序搜索

  • 遍历数组
  • 找到跟目标值相等的元素,就返回它的下标
  • 遍历结束后,如果没有搜索到目标值,就返回 -1
// 时间复杂度 O(n)
Array.prototype.sequentialSearch = function(item){
    for(let i=0; i<this.length;i+=1){
        if(this[i] === item){
            return i;
        }
    }
    return -1;
};

const res = [1,2,3,4,5].sequentialSearch(3)

二分搜索

  • 有序数组,从数组的中间元素开始,如果中间元素正好是目标值,则搜索结束
  • 如果目标值大于或者小于中间元素,则在大于或小于中间元素的那一半数组中搜索

// 时间复杂度 O(logN)
Array.prototype.binarySearch = function(item){
    let low = 0;
    let high = this.length -1;
    while(low <= high){
        const mid = Math.floor((low + high) / 2);
        const element = this[mid];
        if(element < item){
            low = mid + 1;
        }else if(element > item){
            high = mid - 1;
        }else{
            return mid;
        }
    }
    return -1;
};

const res = [1,2,3,4,5].binarySearch(0)
// leetCode 21 合并两个有序链表
// 两个升序链表合并为一个新链表
// 输入 
var mergeTwoLists = function(l1,l2){
    const res = new ListNode(0);
    let p = res;
    let p1 = l1;
    let p2 = l2;
    while(p1 && p2){
        if(p1.val < p2.val){
            p.next = p1;
            p1 = p1.next;
        }else{
            p.next = p2;
            p2 = p2.next;
        }
        p = p.next;
    }
    if(p1){
        p.next = p1;
    }    
    if(p2){
        p.next = p2;
    }
    return res.next;
}

// leetCode 374 猜数字大小
// 二分搜索
var guessNumber = function(n){
    let low = 1;
    let high = n;
    while(low <= high){
        const mid = Math.floor((low + high) / 2);
        const res = guess(mid);
        if(res === 0){
            return mid;
        }else if( res === 1){
            low = mid + 1;
        }else{
            high = mid -1;
        }
    }
}

总结

JavaScript算法

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值