×
By the end of this chapter you should be able to:
Sorting is an important feature to have in any programming language. Whether you want to sort an array of numbers in JavaScript, or a list of strings in Python, it's very common to have a set of data that you want to order in some way.
There are a number of well-known algorithms used to sort data. However, not all of these algorithms are created equal: some are significantly more efficient than others. In this chapter, we'll look at three algorithms that are comparatively more straightforward, even though they aren't the most efficient.
One of the simplest algorithms for sorting an array of elements is bubble sort. The algorithm goes as follows
Here is a nice GIF of the algorithm in action; you can also see an excellent visualization here
And here is a great video describing it in more detail.
So how does the algorithm perform in terms of its time complexity? Unfortunately, the algorithm is typically O(n2) because there's a nesting of loops: you run through the array, and at each iteration you have to run through a subarray of the original array. In the best case scenario, bubble sort will run at O(n) since only one complete iteration will be necessary.
Another simple algorithm for sorting an array of elements is insertion sort. The algorithm goes as follows:
Here is a nice GIF of the algorithm in action; you can also see an excellent visualization here
And here is a great video describing it in more detail.
Like bubble sort, insertion sort typically is O(n2), since you need to go through the array for each element in it in order to find its proper position. In the best case scenario, insertion sort will run at O(n) since only one complete iteration will be necessary.
Another simple algorithm for sorting an array of elements is selection sort. The algorithm goes as follows:
Here is a nice GIF of the algorithm in action; you can also see an excellent visualization here
And here is a great video describing it in more detail.
Just like bubble sort and insertion sort, selection sort is O(n2). In fact, it's O(n2) even in the best case; try to convince yourself why this is true.
Once you feel like you have a solid grasp of these algorithms conceptually, it's time to try implementing them in JavaScript. Complete Part I of the exercises here.
When you're ready, move on to Intermediate Sorting Algorithms