Thursday, September 4, 2025
HomeLanguagesJavascriptp5.js | Bubble Sort

p5.js | Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

In order to know more about it. Please refer Bubble Sort

Approach:

  • Create an array of random values and render a bar corresponding to that value in terms of height.
  • Create a function for bubble sort which compares the adjacent bar in order to swap the bar.
  • In order to get better visualization, set the color to the bar which is currently being processed (red in example shown below).

Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>Bubble Sort</title>
      
    <meta charset="UTF-8">
  
    <script src=
    type="text/javascript"></script>
      
    <style> 
        body {
            padding: 0;
  
        }
        canvas {
            vertical-align: top;
        
    </style>
</head> 
  
<body>
    <script type="text/javascript">
      
        // Set Global Variables 
        let values = [];
        let w = 20;
           
        // To store the state of each bar
        // in order to change the color
        let states = [];
           
           
        function setup() {
              
            // Create Canvas of Size Windows
            // Width * Windows Height
            createCanvas(800, 400);
           
            // Insert Random values in array
            values = new Array(floor(width/w));
           
            for(let i = 0; i < values.length; i++) {
                values[i] = float(random(height));
                states[i] = -1; 
            }
           
            // Print Unsorted Array
            print("Unsorted Array:" + values);
           
            // Call to bubble sort function
            bubbleSort(values, 0, values.length);
           
            // Print Sorted Array
            print("Sorted Array:" + values);
           
        }
           
        // Definition of bubble sort
        async function bubbleSort(arr, start, end) {
            if(start >= end) {
                return;
            }
            
            for(var i = 0; i < end-1; i++) {
                for(var j = 0; j < end-i-1; j++) {
                    if(arr[j] >= arr[j+1]) {
                        states[j] = 1;
           
                        // Call to swap function
                        await swap(arr, j, j+1);
                        states[j+1] = 0;
                    }
                    states[j] = 2;
                }
            }
            return arr;
        }
           
        // Definition of draw function
        function draw() {
            background(51);
              
            for(let i = 0; i < values.length; i++) {
                stroke(0);
                fill(255);
                  
                if(states[i] == 0) {
                    fill(255, 0, 0);
                }
                else if (states[i] == 1) {
                      
                    // Element currently sorting
                    fill("#58FA82");
                }
                else {
                    fill(255);
                }
                rect(i*w, height - values[i], w, values[i]);
            }
        }
           
        // Definition of swap function
        async function swap(arr, a, b) {
             
            await sleep(20);
            let t = arr[a];
            arr[a] = arr[b];
            arr[b] = t;
        }
           
        // Definition of sleep function
        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }
    </script>
</body>
  
</html>            


Output:

RELATED ARTICLES

Most Popular

Dominic
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6627 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS