Cocktail Sort in JavaScript
Just want the code? Scroll all the way down for two versions of the code:
- Without comments (just plug and use).
- With comments to have a better understanding of the code.
What is Cocktail Sort
Cocktail Sort is a variation of Bubble Sort, also known as bidirectional Bubble Sort. It sort items by moving the biggest item on the list to the end, and then reverse and moves the smallest item to the beginning of the list. When compared to bubble sort, the Cocktail Sort does have better improvements but not by much.
I personally found this sorting algorithm very useful when teaching beginners about algorithms, starting with showing them step by step on how to create a bubble sort. After making sure they understand how everything works in a bubble sort, and then asking them to remodel the code into a Cocktail sort.
Steps for Cocktail Sort
- Start from the beginning of the array and use bubble sort to move the largest to the end of the array.
- Start from the end of the array and move the smallest unit to the beginning of the array.
- Repeat Step 1 and 2 until the array is sorted.
Cocktail Sort in JavaScript
There are two ways to code Cocktail Sort, you use a for loop and need two integers to keep track of the beginning and the end of the array as you are pushing the smallest and the largest item into there. Then you stop once the two number is the same so that you are sure you checked and moved every single item on the list. Or you can use a while loop and check if there has been an item that got swapped. If there isn’t, you can now break out of the loop, and you are sure that everything is sorted.
First, we start by declaring a variable called swapped. It is used to keep track if anything has been swapped around within a loop, and if nothing was moved, then the array is sorted and we can return the result.
Then we want to use bubble sort and move the largest element to the end of the array. If an item was swapped, we change the boolean to true, as now we know the array is not sorted.
Now we want to check if everything is sorted, and if it is, we can break out of the loop as it is not necessary to keep going with the reverse bubble sort. Otherwise, we create another bubble sort to move the smallest element to the front of the array.
That is all there is needed for the cocktail sort. Outside the while loop you can just return the array and we have a sorted array.
However, we can still optimize the code a bit. After the first bubble sort, we moved the largest element to the end. Therefore we can update the end index by subtracting one from it. So that in future iterations of the cocktail sort, we don’t need to check that index again.
We can also do the same to the reversed bubble sort and update the beginning of the array so we don’t have to check that in future iterations.