You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用div生成排序可视化图像失败,求技术解决方案

排序可视化代码问题修复方案

原代码核心问题

  • 数组引用重复:visuals.push(array) 存入的是数组的引用,所有步骤最终指向同一个排序完成的数组,无法记录每一步的状态。
  • 可视化元素错误:每个排序步骤只创建1个1px的div,且brightness参数传入整个数组而非单个元素值,完全无法展示排序过程。
  • 样式不可见:1px的宽高太微小,肉眼无法识别,需要调整元素尺寸适配数组值。

修正后的代码

let array = [];
let visuals = [];

// 初始化1-100的数组
let n = 0;
while(n < 100){
    n++;
    array.push(n);
}

// 随机打乱数组
n = 0;
let x, y, temp;
while(n < 100){
    n++;
    x = Math.floor(Math.random() * 100);
    y = Math.floor(Math.random() * 100);
    temp = array[x];
    array[x] = array[y];
    array[y] = temp;
}

console.log("Unsorted:")
console.log(array)
console.log("Sorting: ")

// 冒泡排序并记录每一步状态
let i = 0;
while(i < 100){
    i++;
    n = -1;
    while(n < 100 - i){
        n++;
        if(array[n] > array[n+1]){
            temp = array[n];
            array[n] = array[n+1];
            array[n+1] = temp;
        }
    }
    console.log(array);
    // 复制当前数组状态,避免引用覆盖
    visuals.push([...array]);
}

// 生成可视化元素
visuals.forEach((stepArray, stepIndex) => {
    // 创建每一步的容器,用于区分不同排序阶段
    const stepContainer = document.createElement("div");
    stepContainer.style.display = "flex";
    stepContainer.style.gap = "2px";
    stepContainer.style.marginBottom = "4px";
    
    // 遍历当前步骤的数组元素,创建对应高度的div
    stepArray.forEach(num => {
        const bar = document.createElement("div");
        bar.style.backgroundColor = "#333";
        // 用元素值设置高度,适配可视化
        bar.style.height = `${num * 2}px`;
        bar.style.width = "4px";
        // 可以根据值调整亮度,增强视觉区分
        bar.style.filter = `brightness(${50 + num/2}%)`;
        stepContainer.appendChild(bar);
    });
    
    document.getElementById("output").appendChild(stepContainer);
});

关键修改说明

  1. 数组状态快照:用visuals.push([...array])替代原代码的visuals.push(array),通过扩展运算符复制数组,保存每一步的独立状态。
  2. 步骤容器设计:每个排序步骤创建一个flex布局的容器,将当前步骤的所有元素div横向排列,并用margin区分不同步骤。
  3. 可视化元素优化:
    • 用数组元素值设置div高度(num * 2放大尺寸,方便观察)
    • 调整宽度为4px,增加可见性
    • 亮度计算改为基于单个元素值,实现值越大亮度越高的视觉效果
  4. 代码精简:把n = n + 1简化为n++,提升可读性。

内容的提问来源于stack exchange,提问作者twn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:29:57