- Learning JavaScript Data Structures and Algorithms
- Loiane Groner
- 332字
- 2021-08-27 18:41:18
Sorting elements
Throughout this book, you will learn how to write the most-used searching and sorting algorithms. However, JavaScript also has a sorting method and a couple of search methods available. Let's take a look at them.
First, let's take our numbers array and put the elements out of order (1, 2, 3, ... 15 are already sorted). To do this, we can apply the reverse method, in which the last item will be the first and vice versa, as follows:
numbers.reverse();
So now, the output for the numbers array will be [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]. Then, we can apply the sort method as follows:
numbers.sort();
However, if we output the array, the result will be [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]. This is not ordered correctly. This is because the sort method sorts the elements lexicographically, and it assumes all the elements are strings.
We can also write our own comparison function. As our array has numeric elements, we can write the following code:
numbers.sort((a, b) => a - b);
This code will return a negative number if b is bigger than a, a positive number if a is bigger than b, and 0 (zero) if they are equal. This means that if a negative value is returned, it implies that a is smaller than b, which is further used by the sort function to arrange the elements.
The previous code can be represented by the following code as well:
function compare(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } // a must be equal to b return 0; } numbers.sort(compare);
This is because the sort function from the JavaScript Array class can receive a parameter called compareFunction, which is responsible for sorting the array. In our example, we declared a function that will be responsible for comparing the elements of the array, resulting in an array sorted in ascending order.