Skip to content
Blog

Visualise Bubble Sort in JavaScript (p5.js)

By Published A short read

    One of the most  important thing that we have learnt over the years while learning in data structures and algorithms is that as important is to understand it and to use it. One should also know how to visualize these data structures and algorithms. 

    And we've got you covered in this article we are visualizing the bubble sort algorithm in javascript. And for this we are taking a help of a Javascript library called P5.js you can learn more about it by clicking here. 

    Let me give you a brief description about P5.js to you. Its is a library that helps you in your canvas, animation and simulation projects. In this project we have used downloaded the library but there is a cdn link that you can use in your project. And if you want to learn about the bubble sort algorithm click here. 

    So let's start out project 

Bubble Sort Algorithm Visualizer

  1. Create a project folder.
  2. Create index.js, index.html files in it.
  3. Copy the html code in index.html and javascript code in index.js


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
    content="width=device-width, initial-scale=1.0">
    <title>Visualizer</title>
    <script src="./p5/p5.js"></script>
    <script src="./index.js"></script>
</head>
<body>
</body>
</html>

Above Code is HTML code

let arr = []
let states = []
let i = 0;
let j = 0;

const width = 500, height = 400
let lineWidth, noOfElements = 30
function setup(){
    createCanvas(width, height)
    lineWidth = width / noOfElements
    for(let i = 0; i < noOfElements; i++){
        arr[i] = random(noOfElements)
        states[i] = -1
    }
}              

function draw(){
    background(25)

    if(arr[j] > arr[j + 1]){
        let temp = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = temp
        states[j] = 0
    }
    j = j + 1
    states[j]= -1
    if(i < arr.length){
        if(j >= arr.length - i - 1){
            j = 0
            i = i + 1
        }
    }else{
        noLoop()
    }

    for(let i = 0; i < noOfElements; i++){
        switch (states[i]) {
            case 0:
                fill(200,100,50)
                break;
            default: fill(100,200,50)
                break;
        }
        rect(i*lineWidth,height, lineWidth, -arr[i]*10)        
    }
}

Above is Javascript Code


Below is the output

bubble sort algorithm visualizer in javascript
Output When Sorting Completed


Bubble sort Algorithm Visualizer In Javascript
Output While sorting