Search code examples
javascripthtmlbubble-sort

bubble sort on div using height of div fails


Bubble sort function doesn't sort div's according to their height. Can anyone figure out whats wrong here Try running code multiple times if sorted correctly at first

if statement in bubble sort is exexuted even if condition is false

Here is codepen link to code

Sort function

    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";
      }
    }

Solution

  • The variables ht1 and ht2 will be String objects with a value that is something like "12px". You'll need to parse out the number part of the string and then use parseInt() to convert it to a number. Then do your comparison.

    Alternatively, this will work (but not recommended) parseInt("12px") ie parseInt(ht1) > parseInt(ht2)