• 技术文章 >Web开发 >JavaScript

    js如何合并两个有序数组

    小妮浅浅小妮浅浅2021-11-17 15:13:53原创13621

    1、新建空数组res存储最终排序后的数组。

    2、比较两个有序数组的头部,年轻人出队推进res。

    3、如果两个数组仍然值得,重复第二步。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

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

    以上就是js合并两个有序数组的方法,希望对大家有所帮助。更多js学习指路:js教程

    推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

    专题推荐:js数组
    上一篇:js中二分搜索的使用 下一篇:js事件委托的优点

    相关文章推荐

    • js数组去重并升序• js数组排序方法sort• js数组求和函数• js数组使用es6遍历方法• js数组求i到j的和• js数组遍历map方法• js数组求和reduce• js数组在头部或尾部插入元素的方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网