JavaScript Functions - Bubble Sort algorithm
NOTE: in this article I used bubble sort to provide more function examples.
Bubble Sort Algorithm
Bubble Sort is a sorting algorithm, which is commonly used in computer science. Bubble Sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.
Steps on how it works
Unsorted array: [40, 20, 30, 10, 60, 15, 0, 1]
Always sorted in Ascending order. (swap)
- Start with the first two elements and sort them in ascending order. we compare the element to the adjacent elements to check which one is greater, and swap.
- Compare the second and third element to check which one is greater, and swap
- Compare the third and fourth element to check which one is greater, and swap
- Compare the fourth and fifth element to check which one is greater, and swap
- Compare the fifth and sixth element to check which one is greater, and swap
- Compare the sixth and seventh element to check which one is greater, and swap
- Compare the seventh and eight element to check which one is greater, and swap
Repeat steps 1–7 until no more swaps are required.
Please see below for code and example of the output:
Thanks for reading this article.