JavaScript

Bubble Sort in JavaScript

Let suppose we have an unsorted array and we are asked to sort the array in any ascending, or descending order. Bubble sort is one of the simplest sorting algorithms that compares two side-by-side items and sorts the array. Numerous algorithms are available to sort the arrays, such as selection sort, and merge sort, etc. In this article, we will learn how to use bubble sort in order to sort the array elements.

Working of Bubble Sort

Suppose we want to sort our array in ascending order. It starts working by comparing the left index to the right index. Initially, it will compare the values of the first two indexes of the array. The value of the 0th index will be replaced only when the 1st index carries a smaller value than the 0th index’s value.  Next, it will compare the value of index 1 with the value of index 2, and so on.

Suppose we have the following unsorted array:

https://lh5.googleusercontent.com/lIATtPToelt3P3bL5cFY4mn8KsWG54Km-Xd8Pleib3HJwolk4l7dRkP8C_D3tYfNHFHmySOiFrR7gn0N3hFxubgpEKAm4tVB412cKyIZwCywgYIPNVGBNCDYFjFNeT9HyYeunjWa

We know that in arrays indexing starts from 0. So initially, “8” is stored at the 0th index, “3” is stored at the first index, “1” is stored at the second index, and so on. Now, we have to sort this array in ascending order as shown in the below-given array:

https://lh3.googleusercontent.com/3O4qmaJR1vAv_Z0SlLS36GNceQSBhHcpk-do8ZkoVdtqqNkUtBkjL9xTKbSaiYZDwhh96OTXyQkn8CLpTJpRc2kCh73XX_S89R1ekmNZRq1lv-noC3Cm8urD3wOdkYfszaklVSjR

Now, we will explain the working of bubble sort step by step.

 

Step 1

In the beginning, index 0 carries 8 while index 1 carries 3. Since we have to sort the array in ascending order, therefore, the value of index 0 will be replaced with the value of index 1. Now, the updated array will be:

https://lh6.googleusercontent.com/zdbWmDnddSPVtZJ7dZ1qaZ1sojbHGc8Cj4m3vbEXrqdQHGSUE6nojFmO6ZmXVfKGpFuSv90zb-07Rmet5pLlRE8syFxTXxlswiffohP2kn_aLg0H4GDBJ3enfMC-tmxYrBIZLQ-9

Now the value of index 1 will be compared with the value of index 2. The value of index 1 is 8 while the value of index 2 is 1 which is less than 8, so it will be swapped and the array will be modified as:

 

https://lh3.googleusercontent.com/R77jWMCJ0VxuppLk9wPKpeWlNMDezrK8arnZT-aEG7xGWUde3qszeDLQjlAwIq1ALxFXC5v0C5sdbbPDNG5-hYjJaGD2e7Fi49727cRvZEw5YM7hQRd9msbcRGTFyPLJSLa_aSsE

Now, we will make a comparison between index 2 and index 3. The value of index 2 is 8 which is greater than the value of index 3 which is 2 so the values will be swapped:

 

https://lh6.googleusercontent.com/cbX814aNJHqgsx6cTVyAGv563WUpTyK57tauOcttqPsEk8X3B23StqtFvOrEFHhr52-qn6840hzswNw85phIdzn58t-8JIKZHoD7smiA6WPMUYDQdPaNLPXPGfjfLUW44NdGxVpf

Now compare the value of index 3 with the value of index 4. At index 3 value is 8 while at index 4 value is -1 which means both these values will be swapped:

https://lh5.googleusercontent.com/rCTely2lhq94OZ4GilK2XSylqYEqcAQaoIw8flLxLFT5qIEiQFhqnC93BwA9xbH-VwcDZKyicMJiTlmpeYrnhikT3r9UXdxDTzoj3-XldV_Z2XNkJMlIlENppVBKiMzd0iG-PIhd

Finally, the value of index 4 will be compared with the value of index 5. Again 8 is greater than 7 so, it will be replaced with 7:

https://lh4.googleusercontent.com/huc4V2FkWAoj9ciDxK69v1WaOu7mtTzpcCrOJfh97lZwcffU2ZVuH3MtNB59SFwYYNUHACGLjWYsMaqh4SLOli3yaZUH0adra2Ideg5g8j22CpWVue53PBqwera-MNMhBTfAlzDP

Now, the first iteration is complete, and “8” reaches its appropriate position. So, in the next step, the comparisons will be made till the 4th index since the value of the last index is sorted.

Step 2:

Now, the first two indexes will be compared. The value of the 1st index is less than the value of the 0th index therefore there values will be swapped:

https://lh6.googleusercontent.com/SqcdIflnP4c4LxbCuHaHeYTSdc3N6dvxnb2OWcsVZsIqBZovwJbf8mjFASKch6b3qm0wP-TQXaGWTL2pPvriXrgRiwP37_nhRubZFrvQVh7UBKA41mSyQsMzQJwukxm-v5RIpxLg

Next, we will compare the value of the 1st index with the value of the 2nd index. Here, 3 is greater than 2 so, it will be replaced with 2:

https://lh5.googleusercontent.com/kzJ2MSrF2nOotHJ8XYXm7BPYY4hqe-p651h1v-DrotdjJ5Q-Q6oHeoMRFI0g3iLGOrpOhfj1DsAVjqXfy1L71b268_tTanbYCw0OqfDbJktSkrzlSrKVhGWnpXW3IRWqMlK3N0Hn

Now we will compare the value of 2nd and 3rd index i.e. 3(at 2nd index) with the value of the 3rd index which is -1. Values will be swapped again since 3 is greater than -1:

https://lh6.googleusercontent.com/bSM3kcCDiFhTWGhtxcdYDzfIWB5lsuUOybFfUtD_esx_tb84OHWaaiYfxsO3sJcqH1MdqYTyflWqN8S1FjXwXyfdwU4c-vg3m2PLc29VwNnGDpLzxyAIW3nAAjpg5XmHrDt2osjH

The value of the 3rd index is already less than the value of the 4th index so, it will remain the same:

https://lh6.googleusercontent.com/K5V06ZT9M-YEYIJx5k3f4ByNEyJNR-lNS7-GQzfGIXlWsD2MuCh-QSafBEc-rSGTmrUF-C0OZPml5YwCMJ1N9M5yF9sr5jggWY1uj2-bOVcbqPH7aniO4S0W7JgTzOoatp22zs0-

Now the last two indexes are sorted and the values are placed properly on the 4th and 5th indexes.

Step 3:

Now in this iteration, initially the value of the 0th index will be compared with the value of the 1st index. Here, the value of the 0th index is 1 which is already less than the value of the 1st index which is 2. So, these values will remain the same.

https://lh6.googleusercontent.com/dW9osVvFY-6G-0l32gdNkxnhfL7zfqWric8ThQ8otjNfYmwt5p97p_wcGYr-jpuitzE9UYQw3EfUe9zi_jWn6mNRqClxaUZmMQKLUJuE5WCnJtf1kP6AAaYALgpWtpF3JteS4QnO

Next, compare the next two indexes, here the value of the 1st index is greater than the value of the 2nd index therefore, their values will be swapped:

https://lh4.googleusercontent.com/g51LNuSJc4F1i2-HVYTwXQGQynjVlvlohf5xfgn2j7WsVgCDCFqQ-6Naizv73XAQm2N-b6j26KnD9-2699LxOeeJYXVBwPQ7AJ08YHKg6dGGxCiccLVQG3i-D5ECWtgoe-DqitB2

The value of the 2nd index is already less than the value of the 3rd index therefore, their values will not be swapped:

https://lh5.googleusercontent.com/zYgLxzq2xu6zYo9eyF-OnZ9fxrPIKDIaFqfbFzYDkQA2geMXmlahm1xEny2Mofw53idfMO4W7ELxR9_eTj_rcn6GRgzAy-N_Hz-G2wwVclxa5FATOlJdGOXx_o73OEFxJABiD47B

Step 4:

Compare the first two indexes. The value of the 0th index is 1, which is less than the value of the 1st index(-1), so it will be swapped:

https://lh6.googleusercontent.com/6AbyyCn1c-puQCkTJmnRBdnUtZAR8qglfzkR7YMiBWWKScM8pdQUIQTOrMQCBw2d6QUbhPr0CZUzlhWc_8qyaRc1thh8LZfVhHwkfKsf8oN3esM3bDVY1eou18su5Uz2xHP_6fxd

Next, we will compare the value of the 1st index with the value of the 2nd index. They are already sorted, so they will remain the same:

https://lh5.googleusercontent.com/oein6H-ZZT6CQK4-9AxNzSLBBHwNu6hBFZ9ZPcDFegBLa2YAobDPCNmxYjCZoOR8QcdW9Xt_4UTc4uNnDc4farCOZPyx7HTSipo6Jlv-HBfWvxG9bd3DrsofMRebUWOEcj6fWpQG

Finally, our array is sorted in ascending order.

 

Implementation of Bubble Sort in JavaScript

Since we understood how bubble sort works, now we will implement this logic in JavaScript using nested loops:

functionbubbleSort(ary){
    leti, j;
    varflag = false;
       
    for(i =0; i<ary.length; i++)
    {
        flag = false;
        for(j = 0; jary[j + 1])
            {
            vartemp = ary[j]
            ary[j] = ary[j+1];
            ary[j+1] = temp;
            flag = true;
            }
        }
        if(!flag)
        {
        break;
        }
    }
    console.log(ary)
    }
    varary = [8, 3, 1, 2, -1, 7];
    bubbleSort(ary);

https://lh6.googleusercontent.com/Vs4ri0LxcOciNjKva5tzb-fNarNMeJhvuXDKQI3lzg-Vm18NyVC1emXNQUIHEFT88m2zro7t_HInK5jwAGgUW0uE0Xv3UX1BtEuESCArRaj9_BGJfs53CGxwi6_wROqcz1S0_cmr

In the above-given code, we created an array named ‘ary’ and assigned some data to it. Afterwards, we created a function named bubbleSort and we passed the array to it. A variable named ‘flag’ is initially assigned with a value ‘false’. This flag will be used to verify if the array is completely sorted out or not. Next, the for-loop is initialized with the 0 and it will execute until it is less than the array length.

Nested for-loop is utilized to draw a comparison of the value at the current index with the value at the adjacent index, the values will be swapped only if the value of the current index is higher than the value present at its adjacent index. The value of the flag will be replaced with true if any value is swapped during iteration.

Once the inner loop is done, the flag variable is checked. If the flag variable stays false, it means that the array is already sorted out and the inner loop has not changed anything. In such a case, simply break the loop.

Finally, the array is passed to the bubbleSort() function. The output will be:

Conclusion

Bubble sort is a basic sorting algorithm that swaps the side-by-side elements over and over again until they are not in proper order. In this article, we presented all the basics and essential knowledge needed to understand the concept of bubble sort in JavaScript. Starting with the introduction that described what bubble sort is and how it works. Then we took an example to understand the concept of bubble sort. Furthermore, we implemented the same example in JavaScript and discussed its working in detail.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.