Sorting!
--
No we are not at Hogwarts, but I am 100% a Ravenclaw. When it comes to software engineering and sorting, we are rearranging the items in a collection so that the items are in some kind of order. Anything can technically be sorted and there are a bunch of ways to sort, however for this blog I am going to focus mainly on assorting numbers in an array.
As stated before, there are many types of ways people sort. You can sort by size, you can sort alphabetically, you can even sort an array of movies based off of the mount of money they made in the box office. The purpose of sorting is so that your data can be organized. It also doesn’t hurt that sorting data is also a classic interview topic.
Javascript has a built in method, sort()
. This is definitely a nice method to have on hand, however it doesn’t always work the way you want it to. It first accepts an optional comparator function. You can use this comparator function to tell JS how you want it to sort.
The comparator looks at pairs of elements (a and b), and determines their sorted order based on the return value. So, if it returns a negative number, “a” should come before “b”. If it is a positive number, “a” should come after “b”. However, if it returns a 0, “a” and “b” are the same as far as the sort is concerned, and that isn’t always the case.
A cool sorting method I recently learned, was the Bubble Sort Method. This is a sorting algorithm where the largest values within an array bubble up to the top. As the function loops through the array, it compares the value of one element to the one in front of it. If it is larger, swap it to the front.
A key thing to remember though is to make sure that you have a break point. The break point is important to have so that if you have an array that is close to being finished, you won’t have to loop over every element if it finishes early.
Another important item to have in your function is to make sure that it doesn’t go too far. This is so that you don’t have a needless comparison. To solve this solution you have your i=array.length; i>0; i--
. This now makes it so that after the first loop you don’t loop after the last element that is the max.
Below you will find an example of this code: