p5.js | Bubble Sort - GeeksforGeeks

09 Jul, 2019
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="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"    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:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?