JavaScript Searching and Sorting Algorithm: Bubble sort

JavaScript Searching and Sorting Algorithm: Exercise-7 with Solution

Write a JavaScript program to sort a list of elements using Bubble sort.

According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position."

Step by step pictorial presentation :

C sarp - Bubble sort

Sample Solution: -

HTML Code:

<!DOCTYPE html>
  <meta charset="utf-8">
  <title>JavaScript program of Bubble sort</title>

JavaScript Code:

function swap(arr, first_Index, second_Index){
    var temp = arr[first_Index];
    arr[first_Index] = arr[second_Index];
    arr[second_Index] = temp;

function bubble_Sort(arr){

    var len = arr.length,
        i, j, stop;

    for (i=0; i < len; i++){
        for (j=0, stop=len-i; j < stop; j++){
            if (arr[j] > arr[j+1]){
                swap(arr, j, j+1);

    return arr;
console.log(bubble_Sort([3, 0, 2, 5, -1, 4, 1]));

Sample Output:



JavaScript Searching and Sorting Algorithm Exercises: Bubble sort

Live Demo:

See the Pen searching-and-sorting-algorithm-exercise-7 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to sort a list of elements using Shell sort.
Next: Write a JavaScript program to sort a list of elements using Cocktail shaker sort.

What is the difficulty level of this exercise?

JavaScript: Tips of the Day

Returns the distance between two points


const tips_distance = (p0, q0, p1, q1) => Math.hypot(p1 - p0, q1 - q0);
console.log(tips_distance(1, 3, 5, 7));