(十一)进阶算法之“搜索排序”

69 阅读4分钟

@TOC

排序和搜索简介

排序和搜索是什么?

排序:把某个乱序的数组变成升序或者降序的数组 搜索:找出数组中某个元素的下标

JS中的排序和搜索

JS中的排序:数组的sort方法 JS中的搜索:数组的indexOf方法

排序算法

冒泡排序,O(n^2) 选择排序,O(n^2) 插入排序,O(n^2) 归并排序,O(n * logN) 快速排序,O(n * logN) ......

搜索算法

顺序搜索,O(n) 二分搜索,O(logN) ......

Javascript实现:冒泡排序

冒泡排序的思路 比较所有相邻元素,如果第一个比第二个大,则交换它们 一轮下来,可以保证最后一个数是最大的 执行n-1轮,就可以完成排序

可以在visualgo.net/zh/sorting网站上查看算法动画效果

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();

时间复杂度O(n^2)

Javascript实现:选择排序

选择排序的思路 找到数组中的最小值,选中它并将其放置在第一位 接着找到第二小的值,选中它并将其放置在第二位 以此类推,执行n - 1轮

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)

Javascript实现:插入排序

插入排序的思路 从第二个数开始往前比 比它大就往后排 以此类推进行到最后一个数

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, 5, 3, 1];
arr.insertionSort();

时间复杂度O(n^2)

Javascript实现:归并排序

归并排序的思路 分:把数组劈成两半,再递归地对子数组进行“分操作”,直到分成一个个单独的数 合:把两个数合并为有序数组,再对有序数组进行合并,直到全部子数组合并成一个完整数组 合并两个有序数组 新建一个空数组res,用于存放最终排序后的数组 比较两个有序数组的头部,较小者出队并推入res中 如果两个数组还有值,就重复第二步

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 = [5, 4, 3, 2, 1];
arr.mergeSort();

分的时间复杂度是O(logN) 合的时间复杂度是O(n) 时间复杂度:O(n * logN)

Javascript实现:快速排序

快速排序的思路 分区:从数组中任意选择一个“基准”,所有比基准小的元素放在基准前面,比基准大的元素放在基准的后面 递归:递归地对基准前后的子数组进行分区

Array.prototype.quickSort = function () {
    const rec = (arr) => {
        if (arr.length === 1) { return arr; }
        const left = [];
        const right = [];
        const mid = arr[0];
        for (let i = 1; i < arr.length; i += 1) {
            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, 5, 3, 1];
arr.quickSort();

递归的时间复杂度是O(logN) 分区操作的时间复杂度是O(n) 时间复杂度:O(n * logN)

Javascript实现:顺序搜索

顺序搜索的思路 遍历数组 找到跟目标值相等的元素,就返回它的下标 遍历结束后,如果没有搜索到目标值,就返回-1

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(0);

时间复杂度O(n)

Javascript实现:二分搜索

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

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);

每一次比较都使搜索范围缩小一半,时间复杂度O(logN)

LeetCode:21.合并两个有序链表

在这里插入图片描述 解题思路 与归并排序中的合并两个有序数组很相似 将数组替换成链表就能解此题 解题步骤 新建一个新链表,作为返回结果 用指针遍历两个有序链表,并比较两个链表的当前节点,较小者先接入新链表,并将指针后移一步 链表遍历结束,返回新链表 在这里插入图片描述 时间复杂度O(n),n是两个链表长度之和,空间复杂度是O(1)

LeetCode:374.猜数字大小

在这里插入图片描述 解题思路 这不就是二分搜索嘛 调用guess函数,来判断中间元素是否是目标值 解题步骤 从数组的中间元素开始,如果中间元素正好是目标值,则搜索过程结束 如果目标值大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找

在这里插入图片描述 时间复杂度O(logn),空间复杂度是O(1)

思考题

1、Chrome 最新的 Array.prototype.sort 用的是什么排序算法? 2、用二分搜索算法求 x 的平方根。题目链接:leetcode-cn.com/problems/sq…