首页 > 解决方案 > 使用 div 的高度对 div 进行冒泡排序失败

问题描述

冒泡排序功能不会根据高度对 div 进行排序。谁能弄清楚这里出了什么问题 如果一开始排序正确,请尝试多次运行代码

即使条件为假,如果冒泡排序中的语句被执行

这是代码的codepen链接

排序功能

    function resolveAfterXSeconds(x) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(x);
        }, x * 1000);
      });
    }

    function swap(el1, el2) {
      const style1 = window.getComputedStyle(el1);
      const style2 = window.getComputedStyle(el2);

      const transform1 = style1.getPropertyValue("height");
      const transform2 = style2.getPropertyValue("height");

      el1.style.height = transform2;
      el2.style.height = transform1;
      console.log(`swapped ${transform1} ${transform2}`);
    }

    async function bubble_sort() {
      let arr = document.querySelectorAll(".bar");

      for (let i = 0; i < arr.length - 1; i++) {
        // let i = 0;
        for (let j = 0; j < arr.length - i - 1; j++) {
          arr[j].style.background = "red";
          arr[j + 1].style.background = "red";

          const ht1 = arr[j].style.height;
          const ht2 = arr[j + 1].style.height;
          if (ht1 > ht2) swap(arr[j], arr[j + 1]);
          await resolveAfterXSeconds(0.5);

          arr[j].style.background = "yellow";
          arr[j + 1].style.background = "yellow";
        }
        arr[arr.length - i - 1].style.background = "green";
      }
    }

标签: javascripthtmlbubble-sort

解决方案


变量ht1ht2将是字符串对象,其值类似于“12px”。您需要解析出字符串的数字部分,然后parseInt()将其转换为数字。然后做你的比较。

或者,这将起作用(但不推荐),parseInt("12px")parseInt(ht1) > parseInt(ht2)


推荐阅读