DEV Community is a community of 783,060 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. Bubble sort Algorithm

Hello Guys today i am going to show you how to apply bubble sort algorithm. The Language i have used is javascript and for the frontend end or GUI part HTML AND CSS and The React JS Framework.

Lets get started...

What is Bubble Sort Algorithm?
Bubble sort algorithm is an algorithm that sorts the array by comparing two adjacent elements and swaps them if they are not in the intended order. Here order can be anything like increasing order or decreasing order.

How Bubble-sort works
We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ] the task is to sort the array using bubble sort.

Bubble sort compares the element from index 0 and if the 0th index is less than 1st index then the values get swapped and if the 0th index is less than the 1st index then nothing happens.

then, the 1st index compares to the 2nd index then the 2nd index compares to the 3rd, and so on…

Syntax
BubbleSort(array){
for i -> 0 to arrayLength
for j -> 0 to (arrayLength - i - 1)
if arr[j] > arr[j + 1]
swap(arr[j], arr[j + 1])
}

Implementation -

import React from 'react'
import './App.css';

function App() {

// Creating the bblSort function
function bblSort(arr){

for(var i = 0; i < arr.length; i++){

// Last i elements are already in place
for(var j = 0; j < ( arr.length - i -1 ); j++){

// Checking if the item at present iteration
// is greater than the next iteration
if(arr[j] > arr[j+1]){

// If the condition is true then swap them
var temp = arr[j]
arr[j] = arr[j + 1]
arr[j+1] = temp
}
}
}

}

// This is our unsorted array
var arr = [234, 43, 55, 63, 5, 6, 235, 547,100,98,70,900,80,1];
const UnSortedArray = arr.map((number) =>
<li>{number}</li>
);

//function calling
bblSort(arr)

//this is our sorted array
const SortedArray = arr.map((number) =>
<li>{number}</li>
);

return (
<div className='main-div'>
<div className='bg-dark text-light text-center'>
<h1 className='display-3 text-light my-3'>Unsorted Array</h1>
<ul>
{UnSortedArray}
</ul>
</div>
<div className='bg-primary text-light text-center'>
<h1 className='display-3 text-light my-3'>Sorted Array Using Bubble Sort</h1>
<ul>
{SortedArray}
</ul>
</div>

</div>
);
}

export default App

CSS Part -

.main-div{
display: grid;
place-content: center;
grid-template-columns: repeat(2,1fr);

}

.main-div > div{
}

ul{
list-style-type: none;

}

ul > li{
font-size: 25px;
}

NOTE - I have used bootstrap in the code so please install it either through npm or using cdn.

THANK YOU FOR READING THIS POST IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION PLEASE MENTION IT IN THE COMMENT SECTION.