Bubble sort is the most common and simplest of all the sorting algorithms. In bubble sort, two elements of an array are compared and then swapped accordingly.

At the end of the first pass, the largest element is shifted or bubbled to the end of the array. This continues until the whole array is sorted.

Let’s understand with the help of an example.

`[8, 2, 1, 3, 9] `

-> The sorting starts from the first index, compares the first to elements.
`[2, 8, 1, 3, 9]`

-> Since 8 > 2, they are swaped. Next, 8 is compared with next element i.e. 1.
`[2, 1, 8, 3, 9]`

-> 8 > 1, they are swaped. Next, 8 is compared with the next element i.e. 3.
`[2, 1, 3, 8, 9]`

-> 8 > 3, they are swaped. Next, 8 is compared with the next element i.e. 9.
`[2, 1, 3, 8, 9]`

-> Now, as the last two elements are already in order, the algorithm moves to the next pass.

The next pass will again start from the first element and this will continue until the sorting is done.

Following is the implementation of bubble sort using JavaScript.

let arr = [8, 2, 1, 3, 9] let l = arr.length for (let i = 0; i < l; i++) { for (let j = 0; j < l; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } console.log(arr) //[1, 2, 3, 8, 9]

So in bubble sort implementation, two for loops are used and, in the nested for loop, swapping is performed. The average time complexity of bubble sort is O(n^2) and space complexity is O(1).

Previous Article

Big O notation In Javascriptjavascript algorithms - Insertion sort Explained using Javascript .

January 11, 2021

1 min

Big O notation In Javascript

January 07, 2021

3 min

forEach() Method in javascript and how to use it .

January 04, 2021

1 min

Functional programming in javascript

December 06, 2020

2 min

Closures in Javascript for beginners

December 01, 2020

3 min

Quick Links

Legal Stuff