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 :

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:

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
JavaScript: Performs left-to-right function composition for asynchronous functions
Example:
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); const sum = pipeAsyncFunctions( a => a + 1, a => new Promise(resolve => setTimeout(() => resolve(a + 2), 1000)), a => a + 3, async a => (await a) + 4 ); (async () => { console.log(await sum(5)); })();
Output:
15
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework