w3resource

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>
  <html>
  <head>
  <meta charset="utf-8">
  <title>JavaScript program of Bubble sort</title>
  </head>
  <body></body>
</html>

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:

[-1,0,1,2,3,4,5]

Flowchart:

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

Example:

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

Output:

5.656854249492381