Bucket Sort Visualization Using Javascript
Last Updated :
17 May, 2023
GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Bucket Sort using JavaScript. We will see how the elements are stored in Buckets and then how Buckets get traversed to get the final sorted array. We will also visualize the time complexity of Bucket Sort.
Refer:
Approach:
- First, we will generate a random array using Math.random() function.
- Different color is used to indicate which element is being traversed.
- Each traversed element is thrown into a suitable Bucket.
- These buckets are sorted using Insertion Sort.
- Further, these buckets are traversed to get the final sorted array.
- Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process.
- The new array can be generated by pressing the “Ctrl+R” key.
- The sorting is performed using BucketSort() function using Buckets.
Example: In this example, we will see the bucket sorting method.
Before Sorting
After Sorting
Below is the program to visualize the Bucket Sort algorithm.
File name: index.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<br />
<p class="header">Bucket Sort</p>
<div id="array"></div>
<br />
<br />
<div style="display: flex; justify-content: space-evenly">
<div class="bucket">
<div id="one" class="bucket2"></div>
<br />
<h3 style="text-align: center">[1-5]</h3>
</div>
<div class="bucket">
<div id="two" class="bucket2"></div>
<br />
<h3 style="text-align: center">[6-10]</h3>
</div>
<div class="bucket">
<div id="three" class="bucket2"></div>
<br />
<h3 style="text-align: center">[11-15]</h3>
</div>
<div class="bucket">
<div id="four" class="bucket2"></div>
<br />
<h3 style="text-align: center">[16-20]</h3>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
style.css: The following is the content for “style.css” used in the above file.
CSS
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.header {
font-size: 20px;
text-align: center;
}
#array {
background-color: white;
height: 265px;
width: 598px;
margin: auto;
position: relative;
margin-top: 64px;
}
.block {
width: 28px;
background-color: #6b5b95;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
}
.block_id {
position: absolute;
color: black;
margin-top: -20px;
width: 100%;
text-align: center;
}
.block_id2 {
position: absolute;
color: black;
margin-top: 22px;
width: 100%;
text-align: center;
}
.block_id3 {
position: absolute;
color: black;
margin-top: 1px;
width: 100%;
text-align: center;
}
.bucket {
width: 256px;
height: 260px;
position: relative;
}
.bucket2 {
margin: auto;
width: 148px;
height: 260px;
}
.firstbucket {
width: 28px;
background-color: #6b5b95;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
}
.secondbucket {
width: 28px;
background-color: #6b5b95;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
}
.thirdbucket {
width: 28px;
background-color: #6b5b95;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
}
.fourthbucket {
width: 28px;
background-color: #6b5b95;
position: absolute;
bottom: 0px;
transition: 0.2s all ease;
}
script.js: The following is the content for the “script.js” file used in the above HTML code.
JavaScript
let container = document.getElementById("array");
// Function to randomly shuffle the array
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
// Generate random number
let j = Math.floor(Math.random() * (i + 1));
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
function generatearray() {
// Creating an array
let arr = [];
// Filling array with values from 1 to 20
for (let i = 0; i < 20; i++) {
arr.push(i + 1);
}
// Shuffling the array
shuffle(arr);
for (let i = 0; i < 20; i++) {
let value = arr[i];
// Creating element div
let array_ele = document.createElement("div");
// Adding class 'block' to div
array_ele.classList.add("block");
// Adding style to div
array_ele.style.height = `${value * 13}px`;
array_ele.style.transform = `translate(${i * 30}px)`;
// Creating label element for displaying
// size of particular block
let array_ele_label = document.createElement("label");
array_ele_label.classList.add("block_id");
array_ele_label.innerText = value;
// Appending created elements to index.html
array_ele.appendChild(array_ele_label);
container.appendChild(array_ele);
}
}
async function InsertionSort(clsnam, delay = 600) {
let blocks = document.getElementsByClassName(clsnam);
blocks[0].style.backgroundColor = "rgb(49, 226, 13)";
for (let i = 1; i < blocks.length; i += 1) {
let j = i - 1;
// To store the integer value of ith block to key
let key = parseInt(blocks[i].childNodes[0].innerHTML);
// To store the ith block height to height
let height = blocks[i].style.height;
// Provide darkblue color to the ith block
blocks[i].style.backgroundColor = "darkblue";
// To pause the execution of code for 600 milliseconds
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 600)
);
// For placing selected element at its correct position
while (j >= 0 && parseInt(blocks[j].childNodes[0].innerHTML) > key) {
// Provide darkblue color to the jth block
blocks[j].style.backgroundColor = "darkblue";
// For placing jth element over (j+1)th element
blocks[j + 1].style.height = blocks[j].style.height;
blocks[j + 1].childNodes[0].innerText =
blocks[j].childNodes[0].innerText;
j = j - 1;
// To pause the execution of code for 600 milliseconds
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, delay)
);
// Provide lightgreen color to the sorted part
for (let k = i; k >= 0; k--) {
blocks[k].style.backgroundColor = " rgb(49, 226, 13)";
}
}
// Placing the selected element to its correct position
blocks[j + 1].style.height = height;
blocks[j + 1].childNodes[0].innerHTML = key;
// To pause the execution of code for 600 milliseconds
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, delay)
);
// Provide light green color to the ith block
blocks[i].style.backgroundColor = " rgb(49, 226, 13)";
}
}
// Asynchronous CountingSort function
async function CountingSort(delay = 250) {
let blocks = document.querySelectorAll(".block");
let block1 = 0,
block2 = 0,
block3 = 0,
block4 = 0;
// CountingSort Algorithm
for (let i = 0; i < blocks.length; i += 1) {
blocks[i].style.backgroundColor = "#FF4949";
let value =
Number(blocks[i].childNodes[0].innerHTML);
// Creating element div
let array_ele = document.createElement("div");
// Adding style to div
array_ele.style.height = `${value * 13}px`;
// Creating label element for displaying
// size of particular block
let array_ele_label = document.createElement("label");
array_ele_label.classList.add("block_id");
array_ele_label.innerText = value;
array_ele.appendChild(array_ele_label);
// Adding block to first bucket
if (value >= 1 && value <= 5) {
array_ele.classList.add("firstbucket");
var container = document.getElementById("one");
array_ele.style.transform =
`translate(${block1 * 30}px)`;
container.appendChild(array_ele);
block1++;
}
// Adding block to second bucket
if (value >= 6 && value <= 10) {
array_ele.classList.add("secondbucket");
var container = document.getElementById("two");
array_ele.style.transform =
`translate(${block2 * 30}px)`;
container.appendChild(array_ele);
block2++;
}
// Adding block to third bucket
if (value >= 11 && value <= 15) {
array_ele.classList.add("thirdbucket");
var container = document.getElementById("three");
array_ele.style.transform = `translate(${block3 * 30}px)`;
container.appendChild(array_ele);
block3++;
}
// Adding block to fourth bucket
if (value >= 16 && value <= 20) {
array_ele.classList.add("fourthbucket");
var container = document.getElementById("four");
array_ele.style.transform =
`translate(${block4 * 30}px)`;
container.appendChild(array_ele);
block4++;
}
// To wait for 250 milliseconds
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, delay)
);
blocks[i].style.backgroundColor = "#6b5b95";
}
// Performing insertion sort on every bucket
await InsertionSort("firstbucket");
await InsertionSort("secondbucket");
await InsertionSort("thirdbucket");
await InsertionSort("fourthbucket");
// Copying elements from buckets to main array
for (let i = 0; i < 4; i++) {
var bucket_idx = 0;
var block_idx;
if (i == 0) block_idx =
document.getElementsByClassName("firstbucket");
if (i == 1) block_idx =
document.getElementsByClassName("secondbucket");
if (i == 2) block_idx =
document.getElementsByClassName("thirdbucket");
if (i == 3) block_idx =
document.getElementsByClassName("fourthbucket");
for (var j = i * 5; j < 5 * (i + 1); j++, bucket_idx++) {
block_idx[bucket_idx].style.backgroundColor = "red";
// To wait for 300 milliseconds
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 300)
);
blocks[j].style.height =
block_idx[bucket_idx].style.height;
blocks[j].childNodes[0].innerText =
block_idx[bucket_idx].childNodes[0].innerText;
blocks[j].style.backgroundColor = "green";
// To wait for 300 milliseconds
await new Promise((resolve) =>
setTimeout(() => {
resolve();
}, 300)
);
block_idx[bucket_idx]
.style.backgroundColor = "#6b5b95";
}
}
}
// Calling generatearray function
generatearray();
// Calling CountingSort function
CountingSort();
Output:

Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read