How To Visualize Sorting Algorithm In Javascript | Bubble Sort - letsbug
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
- Create a project folder.
- Create index.js, index.html files in it.
- 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 = 400let lineWidth, noOfElements = 30function 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
Output When Sorting Completed |
Output While sorting |
Comments
Post a Comment