# Bubble Sort algorithm using JavaScript

Last Updated : 16 Apr, 2024

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

## How Bubble-sort works?

We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ], and the task is to sort the array using bubble sort in ascending order.

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

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

Let’s see with an example. Here, each step is briefly illustrated:

Comparisons happen till the last element of the array

After each iteration, the greatest value of the array becomes the last index value of the array. In each iteration, the comparison happens till the last unsorted element.

Now comparison reduced one step because the biggest element is at its right place

After all the iteration and comparisons of elements, we get a sorted array.

## 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Â

Javascript ```// Bubble sort Implementation using Javascript // 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 } } } // Print the sorted array console.log(arr); } // This is our unsorted array var arr = [234, 43, 55, 63, 5, 6, 235, 547]; // Now pass this array to the bblSort() function bblSort(arr); ```

Output: Sorted array

`[5, 6, 43, 55, 63, 234, 235, 547]`

Note: This implementation is not optimized. We will see the optimized solution next.

## Optimized Solution

As we discussed the implementation of bubble sort earlier that is not optimized. Even if the array is sorted, the code will run with O(n^2) complexity. Let’s see how to implement an optimized bubble sort algorithm in javascript.

### The syntax for Optimized solution

`BubbleSort(array){    for i -> 0 to arrayLength         isSwapped <- false        for j -> 0 to (arrayLength - i - 1)            if arr[j] > arr[j + 1]                swap(arr[j], arr[j + 1])                isSwapped -> true}`

### Implementation

Javascript ```function bubbleSort(array) { const arrayLength = array.length; let isSwapped; for (let i = 0; i < arrayLength; i++) { isSwapped = false; for (let j = 0; j < arrayLength - i - 1; j++) { if (array[j] > array[j + 1]) { // Swap elements [array[j], array[j + 1]] = [array[j + 1], array[j]]; isSwapped = true; } } // If no two elements were swapped in the inner loop, array is sorted if (!isSwapped) break; } return array; } // Test the function const sortedArray = bubbleSort([45, 23, 3, 5346, 5, 356, 243, 35]); console.log("Sorted Array:"); console.log(sortedArray); ```

Output: Sorted Array

`[3, 5, 23, 35, 45, 243, 356, 5346]`

## Complexities

#### Worst Case and Average case time complexityÂ

If the array is in reverse order then this condition is the worst case and Its time complexity is O(n2).

#### Best case time complexity

If the array is already sorted then it is the best-case scenario and its time complexity is O(n)

Auxiliary Space: O(1)

Previous
Next
Share your thoughts in the comments