Sorting — With JavaScript
There are a lot of different algorithms that are out there to sort data. Whether it is to sort items alphabetically or sort numbers in ascending or descending order. The benefits of doing this are quite intuitive as well, if you’ve ever just looked at unsorted data vs sorted data when data is sorted it’s much easier to read and understand the data. Furthermore, in a previous post about searching, I mentioned searching through data and conducting a binary search and how it was more efficient than a linear search, the data for this type of search needed to be sorted first.
I had mentioned before there are different types of sorting algorithms some are seen as simple algorithms like insertion sort and selection sort, there are efficient algorithms like merge sort and quick sort, there are also others like radix sort which works only for sorting numbers as it uses qualities that are unique to numbers. The simple algorithms for the most part except for some unique cases of data don’t run very efficiently and in terms of big O notation have a time complexity of O(n²). Whereas, the efficient ones much like their label suggests are more efficient and have a time complexity of O(nlogn), which is vastly better. Also, the last algorithm I mentioned above of radix sort has a time complexity of O(nk) which is even better than the others but again will only work with numbers.
If we were looking to code out our simple algorithms which include insertion sort, selection sort, and bubble sort we would need to code each of them out with a nested loop going through and comparing the values. I won’t go through the code for each of them in this post because while they are useful in specific cases they are widely known as less efficient algorithms.
Instead, I will go into more detail and through the code of one of the efficient algorithms merge sort. With merge sort, we split the given array in half and continue to do this recursively until we only have one item in each array. We then merge the arrays back together sorting them as we merge them into a new array. The efficient algorithms are definitely a less intuitive way to do it and harder to explain but they are a lot more efficient.
Above is the code for merge sort using a helper function of merge. Here is an example with a small array of numbers that illustrates what is happening in the function and might help to understand.
Input: [4,2,3,1]
[4,2] [3,1]
[4] [2] [3] [1]
[2,4] [1,3]
Sorted: [1,2,3,4]
The Udemy courses JavaScript Algorithms and Data Structures Masterclass & Master the Coding Interview: Data Structures + Algorithms both explained and helped me understand some of the different sorting algorithms.