javascript - 如何在排序数组中插入值并保持数组排序?

标签 javascript arrays

在数组中插入值并保持数组排序的最佳方法是什么?

例如,这是一个数组

const arr = [1, 4, 23, 45];

我可以使用方法 push 或 splice 添加一个新值,例如 16,我将得到修改后的数组:

[1, 4, 23, 45, 16]

但我需要保持数组排序:

[1, 4, 16, 23, 45]

保持数组有序的更好方法是什么?我应该每次添加新值时都排序,还是检测插入新值所需的索引?

最佳答案

看看复杂性:

  • 排序:最佳情况下的时间复杂度为 O(nlogn)
  • 索引插入:最坏情况下的 O(n)
  • 智能排序:在最佳情况下,使用插入排序等算法的时间复杂度为 O(n),当数组几乎已经排序时,该算法效果非常好
  • 二进制插入:O(logn) 这是首选方式

function  binaryInsertion(arr, element) {
    return binaryHelper(arr, element, 0, arr.length - 1);
}

function binaryHelper(arr, element, lBound, uBound) {
    if (uBound - lBound === 1) {
        // binary search ends, we need to insert the element around here       
        if (element < arr[lBound]) arr.splice(lBound, 0, element);
        else if (element > arr[uBound]) arr.splice(uBound+1, 0, element);
        else arr.splice(uBound, 0, element);
    } else {       
        // we look for the middle point
        const midPoint = Math.floor((uBound - lBound) / 2) + lBound;
        // depending on the value in the middle, we repeat the operation only on one slice of the array, halving it each time
        element < arr[midPoint]
            ? binaryHelper(arr, element, lBound, midPoint)
            : binaryHelper(arr, element, midPoint, uBound);
    }
}

console.log("even array test");
var array = [1,3,4,5,9];
binaryInsertion(array, 2);
console.log(array);

console.log("odd array test");
var array = [1,3,5,7,9,11,13,15];
binaryInsertion(array, 10);
console.log(array);

console.log("beginning and end test");
var array = [2,3,4,5,9];
binaryInsertion(array, 0);
binaryInsertion(array, 10);
console.log(array);

关于javascript - 如何在排序数组中插入值并保持数组排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60702410/

相关文章:

javascript - 在 jQuery 中使用 .fadeOut() 时禁用单击

javascript - 如何在 HTML5 Audio 中控制播放和暂停

javascript - 如何设置自定义对象属性以在 Angular typeahead 中进行过滤?

java - 过滤邻居数组

javascript - 当我单击第 n 个: anchor 时显示第 n 个 :div 1,

javascript - 检测是否加载 Angular 依赖项 [ Angular 路由、 Angular 资源等] 以进行 CDN 回退

javascript - 我们如何在将鼠标悬停在子导航上时停止 Jquery 动画?

java - 一次查找数组 12 个元素的最大值

c++ - 自定义排序算法c++

python - 编辑二维数组中元素的简单方法 Python :