Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements “bubble” to the top of the list.
Efficient algorithms such as quicksort, timsort, or merge sort are used by the sorting libraries built into popular programming languages such as Python and Java. We’ll be working in JavaScript for this one.
Bubble sort works by comparing each element in the array to the one directly in front of it and swapping them if the original element is larger.
Let’s start by implementing a swap method. Python makes it easy to swap using the below one line of code.
In JavaScript it’s slightly more complicated. First we create a temporary variable, then make our first swap, followed by our second swap with the temporary variable.
Or with fat arrow syntax.
Perfect! Now how do we decide if the new helper method needs to be called? We can use a simple for loop as below.
Now how do we set up this function so that every time our swap method is called, our for loop knows to keep checking the rest of the array? We could do a variable called isSorted.
This way isSorted will only be reversed if our if statements pass. That means our array will have to be entirely sorted to get out of the while loop. Full code below: