Bubble sort in JavaScript

Pravin M
2 min readFeb 2, 2024
Bubble sort in JavaScript
Bubble sort in JavaScript

Source: Bubble sort in JavaScript

For more questions and answers visit our website at Frontend Interview Questions

Bubble sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. The algorithm takes its name from the way smaller elements “bubble” to the top of the list. Here is how bubble sort works:

  1. Start at the beginning of the list.
  2. Compare the first two elements. If the first element is greater than the second element, swap them.
  3. Move to the next pair of elements and repeat step 2.
  4. Continue this process until the end of the list is reached.
  5. Repeat steps 1–4 until no swaps are made on a pass through the list.

Here is an example of how bubble sort works on a list of numbers:


Unsorted List: 4, 2, 7, 1, 3

Pass 1: 2, 4, 1, 3, 7
Pass 2: 2, 1, 3, 4, 7
Pass 3: 1, 2, 3, 4, 7

The sorted list is 1, 2, 3, 4, 7.

Code for Bubble sort:-


function bubbleSort(arr){
let n = arr.length;
for(var i=0;i < n;i++) {
for(var j=0;j < (n-i-1);j++) {
if(arr[j] > arr[j+1]) {
var temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
var arr=[2,3,1,4,7,6];
const sortedArray = bubbleSort(arr);
console.log(sortedArray); //output : [1,2,3,4,6,7]

Time complexity and space complexity of Bubble sort:


Time complexity: o(n^2) // as we have nested for loops
Space complexity: o(1) // as we are not storing anything in array, object etc

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

No responses yet