Bubble Sort Algorithm in JavaScript
Tags: algorithms, javascript, beginners, tutorial
Published: 2024-03-24 19:58:26

Bubble sort is an algorithm for sorting elements by repeatedly comparing adjacent pairs and swapping them if they are in the wrong order until the entire list is sorted.

We will sort based on ascending order. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbsje4n5kyfv28gzcwf0.png)

## How Bubble Sort Works:

- Traverse from the left and compare adjacent elements and the higher one is placed on the right side. 
- The largest element is moved to the rightmost end at first. 
- Then continue to find the second largest and place it until the data is sorted.


## Algorithm: 
```
bubbleSort(array)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end bubbleSort
```

![Picture from - Tech Guides](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e9pn1te1h99tp8rhwv07.jpg)

## JavaScript Implementation: 
```javascript
let arr = [12, 8, -5, 6, -8, 2];        // input array. 

bubbleSort(arr);            // bubbleSort() function call. 

function bubbleSort(arr){
    let n = arr.length;     // 'n' is array size. 

    for (let j=0; j<n-1; ++j){
        for (let i=0; i<n-j-1; ++i){
            if (arr[i] > arr[i+1]){
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }

    console.log(arr);           // Print the Sorted Arry. 
}
```

## Output:
```cmd
[ -8, -5, 2, 6, 8, 12 ]
```

## How can we optimize the bubble sort algorithm?
![Thinking guy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f9vrnyzani4ogpa2oz40.png)
All the comparisons are made in the above algorithm even if the array is already sorted. This increases the execution time.
We can optimize by checking if the elements are sorted or not. The value of `swapped` is set to 1 (true) if there occurs a swapping of elements. Otherwise, it is set to 0 (false).

This will reduce the execution time to optimize the bubble sort.

## Optimized Bubble Sort Algorithm
```
bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort
```

```javascript
let arr = [12, 8, -5, 6, -8, 2];        // input array. 

bubbleSort(arr);            // bubbleSort() function call. 

function bubbleSort(arr){
    let swapped = 0;        // check if swapping occurs

    let n = arr.length;     // 'n' is array size. 

    for (let j=0; j<n-1; ++j){
        for (let i=0; i<n-j-1; ++i){
            if (arr[i] > arr[i+1]){
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;

                swapped = 1;
            }
        }
        // no swapping means the array is already sorted. so no need for further comparison. 
        if (swapped == 0) {
            break;
        }
    }

    console.log(arr);           // Print the Sorted Arry. 
}
```
## Output:
```cmd
[ -8, -5, 2, 6, 8, 12 ]
```

Time Complexity: O(N^2)

If you found this helpful, please consider giving it a like. It means a lot to me. Thanks for Reading 🩵⭐

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jzr6vonxsoqanoy57kf.gif)


### Reference: 
- https://www.programiz.com/dsa/bubble-sort
- https://www.opentechguides.com/how-to/article/c/51/bubble-sort-c.html
- https://www.geeksforgeeks.org/bubble-sort/
- https://www.geeksforgeeks.org/time-and-space-complexity-analysis-of-bubble-sort/