Click on the image to restart.

Bubble sort visualization

Sorting algorithms put elements of an array in a certain order.
Let's use the bubble sort to sort numbers from lowest to highest, basically changing something like this:
[9, 1, 0, 4]
to this:
[0, 1, 4, 9].
The bubble sort algorithm is short and simple, but this comes at a price of low efficiency - an ideal subject for a beginning coder!
Lower values 'bubble up' to the top if the array is displayed vertically - hence the name. In our case the array is horizontal, so they 'bubble left' instead.
To make things a little more exciting, we'll assign a different color to each number and display the array after each pass.

One-dimensional array version:

It looks weird because there are some empty lines - we'll add them later when we switch to 2d version.

<html>
  <body>
    <canvas id="myCanvaswidth="720height="200"></canvas>
    <script>
      const canvas = document.getElementById("myCanvas");
      const context = canvas.getContext("2d");
 
      const shuffleLength = 1000;
      const rowLength = 360;
 
 
        const array=[]
        for (let n = 0n < rowLengthn++)
          array[n] = n;
 
 
 
 
 
        for (let n = 0n < shuffleLengthn++) {
          let cell1 = Math.floor(Math.random() * rowLength);
          let cell2 = Math.floor(Math.random() * rowLength);
          let temp = array[cell1];
          array[cell1] = array[cell2];
          array[cell2] = temp;
        }
 
 
      function animate() {
        let swapped = false;
 
 
          for (let i = 1i <= rowLength - 1i++) {
            if (array[i - 1] > array[i]) {
              let temp = array[i - 1];
              array[i - 1] = array[i];
              array[i] = temp;
              swapped = true;
            }
          }
          for (let n = 0n < rowLengthn++) {
            context.fillStyle = `hsl(${array[n]},100%,50%)`;
            context.fillRect(n * 20250);
          }
 
        if (swapped)
          window.requestAnimationFrame(animate);
      }
 
      animate();
    </script>
  </body>
</html>



Lines [1-6] set up the HTML5 Canvas, which we'll use for displaying the array.
[8] how many times to shuffle the elements before the sort - arbitrarily selected
[9] the number of elements
[12] the array to be sorted - empty for now
[13-14] fill the array with numbers: [0, 1, 2, 3...]
[20-26] Shuffle the array. Because of the way we filled the array in [13-14], it is already sorted. To see the bubble sort in action, we have to destroy this order. To do this, we (pseudo-)randomly select two elements and exchange their values. We repeat this process shuffleLength times.
[29-48] Actual sort and visualization:
[30] We assume that no elements will have to be swapped, which means all the elements are already sorted. If the algorithm proves us wrong on this, we know that another iteration is necessary.

[33-40] The Bubble Sort Algorithm
Now you know the terrible truth! This algorithm really consists of only 6 instructions! All that hype about this one small loop! You probably regret navigating to this page, but since you're already here, you might as well finish reading:
[33] For elements 1-360:
[34] If this element has higher value than the previous one:
[35-38] swap the elements: [35] copy the first element to the temp variable
[36] copy the second element to the first one
[37] copy the temporary value to the second element
[38] Because we had to swap elements, our assumption from [30] is no longer true.

[41-44] Visualization:
[41] For each element:
[42] Set the color to the value of
HSL (Hue-Saturation-Lightness) is a method of representing colors. We're using it because for a sequence of numbers 0 through 359 it creates a rainbow. So it's just a method of getting an image (a rainbow) without a lot code.
[43] Draw a 2x50 pixels rectangle.
[46-47] If we swapped elements, the sort may be incomplete - let's check by running another pass.

Here's what it looks like:



Click on the image to restart.


With just a few additional lines we can sort a two-dimensional array, so that we have multiple independent rows (which you saw on top of this page):

<html>
  <body>
    <canvas id="myCanvaswidth="720height="200"></canvas>
    <script>
      const canvas = document.getElementById("myCanvas");
      const context = canvas.getContext("2d");
      const mainArray = [];
      const shuffleLength = 1000;
      const rowLength = 360;
 
      for (let row = 0row < 90row++) {
        const array=[]
        for (let n = 0n < rowLengthn++)
          array[n] = n;
         mainArray[row] = array
      }
 
      for (let row = 0row < 90row++) {
        let array = mainArray[row];
        for (let n = 0n < shuffleLengthn++) {
          let cell1 = Math.floor(Math.random() * rowLength);
          let cell2 = Math.floor(Math.random() * rowLength);
          let temp = array[cell1];
          array[cell1] = array[cell2];
          array[cell2] = temp;
        }
      }
 
      function animate() {
        let swapped = false;
        for (let row = 0row < 90row++) {
          let array = mainArray[row];
          for (let i = 1i <= rowLength - 1i++) {
            if (array[i - 1] > array[i]) {
              let temp = array[i - 1];
              array[i - 1] = array[i];
              array[i] = temp;
              swapped = true;
            }
          }
          for (let n = 0n < rowLengthn++) {
            context.fillStyle = `hsl(${array[n]},100%,50%)`;
            context.fillRect(n * 2row * 222);
          }
        }
        if (swapped)
          window.requestAnimationFrame(animate);
      }
 
      animate();
    </script>
  </body>
</html>

We added a two-dimensional mainArray [7]. What was the array in the previous version is now an element in the mainArray: [15, 19, 32].
Now we have to repeat all the actions for each row: [11, 18, 31].
We draw a 2x2 pixel squares now in [42].

Enjoy the bubbles!


Check out these programming tutorials:

JavaScript:

Goldmine - idle game (~200 lines)

Tunnel run game (~170 lines)

Tower game (84 lines)

Optical illusion (18 lines)

Spinning squares - visual effect (25 lines)

Oldschool fire effect (20 lines)

Fireworks (60 lines)

Animated fractal (32 lines)

Physics engine for beginners

Physics engine - interactive sandbox

Physics engine - silly contraption

Starfield (21 lines)

Yin Yang with a twist (4 circles and 20 lines)

Tile map editor (70 lines)

Sine scroller (30 lines)

Interactive animated sprites

Image transition effect (16 lines)

Your first program in JavaScript: you need 5 minutes and a notepad


Fractals in Excel

Python in Blender 3d:

Domino effect (10 lines)


Wrecking ball effect (14 lines)

3d fractal in Blender Python