将数字插入已排序的数字数组 JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 20:28:17
我们需要编写一个 JavaScript 函数,该函数将已排序的数字数组作为第一个参数,将单个数字作为第二个参数。
该函数应将指定的数字作为第二个参数推送到数组中,而不会扭曲元素的排序。
我们需要在不创建另一个数组的情况下执行此操作。
示例
const arr = [6, 7, 8, 9, 12, 14, 16, 17, 19, 20, 22];
const num = 15;
const findIndex = (arr, val) => {
let low = 0, high = arr.length;
while (low < high) {
let mid = (low + high) >>> 1;
if (arr[mid] < val) {
low = mid + 1;
}else {
high = mid
}
};
return low;
};
const insertAt = (arr = [], num) => {
const position = findIndex(arr, num);
for(let i = position; typeof arr[i] !== 'undefined'; i++){
// 交换而不使用第三个变量 num += arr[i];
arr[i] = num - arr[i];
num -= arr[i];
};
arr.push(num);
};
insertAt(arr, num);
console.log(arr);
输出
这将产生以下输出 −
[ 6, 7, 8, 9, 12, 14, 15, 16, 17, 19, 20, 22 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

