【发布时间】:2021-09-27 05:42:06
【问题描述】:
我正在制作一个排序可视化工具。使用绝对位置,我正在交换条形的变换。这种方法适用于 BubbleSort,但在 QuickSort 中会产生不需要的结果。下面是问题的详细解释。
const PIVOT_COLOR = '#FF4949';
const SORTED_COLOR = '#CB6BF9';
async function pivot(blocks, start = 0, end = blocks.length + 1) {
let pivot = Number(blocks[start].childNodes[0].innerHTML);
let swapIdx = start;
let value;
blocks[start].childNodes[1].style.backgroundColor = PIVOT_COLOR;
for (let i = start + 1; i < blocks.length; i++) {
value = Number(blocks[i].childNodes[0].innerHTML);
blocks[i].childNodes[1].style.backgroundColor = 'blue';
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 500)
);
if (pivot > value) {
swapIdx++;
let arr = [];
blocks.forEach(el => arr.push(el.childNodes[0].innerHTML));
console.log(arr);
//swap(arr, swapIdx, i);
await swap(blocks[swapIdx], blocks[i]);
}
blocks[i].childNodes[1].style.backgroundColor = SORTED_COLOR;
}
await swap(blocks[start], blocks[swapIdx]);
console.log(swapIdx)
blocks[start].childNodes[1].style.backgroundColor = SORTED_COLOR;
return swapIdx;
}
export async function QuickSort(blocks, left = 0, right = blocks.length - 1) {
if (left < right) {
let pivotIndex = await pivot(blocks, left, right);
//left
await QuickSort(blocks, left, pivotIndex - 1);
//right
await QuickSort(blocks, pivotIndex + 1, right);
}
}
function swap(el1, el2) {
let wrapper = document.getElementById('wrapper')
let container = wrapper.childNodes[0];
return new Promise((resolve) => {
var temp = el1.style.transform;
el1.style.transform = el2.style.transform;
el2.style.transform = temp;
window.requestAnimationFrame(function () {
// For waiting for .25 sec
setTimeout(() => {
container.insertBefore(el2, el1);
resolve();
}, 250);
});
});
}
当我交换 swapIdx 和 i swap(blocks[swapIdx], blocks[i]) 时,条形图未在正确的 swapIdx 中交换,如下图所示,但它们被插入到 DOM 中的正确位置。
【问题讨论】:
标签: javascript reactjs algorithm sorting visualizer