跳到主要内容

插入元素

有序插入元素


const array = [];

function insert(item) {
let index = array.length;
while (index > 0) {
index--;
const currentItem = array[index];
array[index + 1] = currentItem;
if (item < currentItem) {
continue;
}
index++;
break;
}
array[index] = item;
}

insert(1);
insert(10);
insert(3);
console.log(array);

插入到指定元素序列之前


const array = [4, 5];
const before = [4, 5];

function insert(item) {
let index = array.length;
let beforeSet = new Set(before);
while (index > 0) {
index--;
const currentItem = array[index];
array[index + 1] = currentItem;
if (beforeSet.has(currentItem)) {
beforeSet.delete(currentItem);
continue;
}
if (beforeSet.size > 0) {
continue;
}
index++;
break;
}
array[index] = item;
}

insert(8);
insert(10);
insert(12);
console.log(array);