By Harsh Tanwar

Today we will learn how we sort an array using bubble sort in Javascript as it sorts the array by comparing two adjacent elements and swaps them if they are not in the intended order.

Bubble sort is a simple sorting algorithm that repeatedly steps through the array to be sorted, it compares each pair of adjacent items and swaps them if they are in the wrong order.

We pass through the array until there is no element to swap and hence the array is sorted.

The algorithm is simple but it is too slow and so it is not as efficient as some other algorithms like insertion sort.

**How does it work:**

**step 1:** We compare the jth and the (j+1)th element, if the jth element is bigger we swap them as here we always need (j+1)th element to be bigger.

**step 2: **then we keep repeating this process until the end of the array. and till the end of this first pass, our last element is the biggest one in the array.

**step 3: **we keep repeating this process till we don't reach the case where no swap is needed.

step 4:the array we get after the last pass is our sorted array.

/* Bubble Sort using Javascript. */ /* Bubble Sort Function */ function bubbleSort(a) { for (var i = 0; i < a.length; i++) { for (var j = 0; j < a.length - i - 1; j++) { /* Check if Element at Current Index is Larger then the Next Index */ if (a[j] > a[j + 1]) { /* If TRUE then swap the Elements */ var temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } /*Now a is Sorted*/ /* Print a */ console.log(a); } /* Unsorted Array */ var a = [8, 5, 3 , 1, 4, 7 , 9]; /* Use Bubble Sort on the Array */ bubbleSort(a); /* By - Harsh Tanwar */

Output -

[1, 3, 4, 5, 7, 8, 9] //sorted array

The time complexity of Bubble Sort is **O(n ^{2})**

Submitted by Harsh Tanwar (harshtanwar)

Download packets of source code on Coders Packet

## Comments