Следующее минимальное значение меняется местами, но не в нужное место, которое я хочу. Я включил ссылку на замедленную анимацию ниже и код javascript для создания бара, функцию сортировки выбора и функцию подкачки, которую использует сортировка выбора.
https://drive.google.com/file/d/1vl2U70a2mcxhjAog2An-27grv8ve-GtP/view?usp=sharing
Может кто-нибудь дать мне знать, как исправить обмен, чтобы сортировка работала? Большое спасибо!
const box = document.querySelector(".data-box");
function createBars(num=20) {
// const num = Math.floor(Math.random() * (50 - 10)) + 10;
if (num && typeof num !== "number") {
alert("First argument must be a typeof Number");
return;
}
for (let i = 0; i < num; i += 1) {
const value = Math.floor(Math.random() * 100)+1;
const bar = document.createElement("div");
bar.classList.add("bar");
bar.style.height = `${value * 3}px`;
bar.style.transform = `translateX(${i * 30}px)`;
const barLabel = document.createElement("label");
barLabel.classList.add("bar__id");
barLabel.innerHTML = value;
bar.appendChild(barLabel);
box.appendChild(bar);
}
}
function swap(el1, el2) {
return new Promise(resolve => {
const style1 = window.getComputedStyle(el1);
const style2 = window.getComputedStyle(el2);
const transform1 = style1.getPropertyValue("transform");
const transform2 = style2.getPropertyValue("transform");
el1.style.transform = transform2;
el2.style.transform = transform1;
// Wait for the transition to end!
window.requestAnimationFrame(function () {
setTimeout(() => {
box.insertBefore(el2, el1);
resolve();
}, 250);
});
});
}
async function selectionSort(delay = 100) {
if (delay && typeof delay !== "number") {
alert("sort: First argument must be a typeof Number");
return;
}
let bars = document.querySelectorAll(".bar");
var min;
for (i = 0; i < bars.length-1; i++) {
min=i;
for (j = i + 1; j < bars.length-1; j++) {
await new Promise(resolve =>
setTimeout(() => {
resolve();
}, delay)
);
const value1 = Number(bars[j].childNodes[0].innerHTML);
const value2 = Number(bars[min].childNodes[0].innerHTML);
if (value1 < value2) {
min = j;
}
}
if (i != min) {
bars[i].style.backgroundColor = "#FF4949";
bars[min].style.backgroundColor = "#FF4949";
await swap(bars[i], bars[min]);
bars = document.querySelectorAll(".bar");
}
bars[i].style.backgroundColor = "#13CE66";
}
}
createBars();