What is sorting?
By sorting, we simply mean to arrange items in a particular order. The items may be placed alphabetically, increasingly or decreasingly. The words can be arranged alphabetically whereas numbers can be arranged in increasing or decreasing order.
sort() method in arrays to arrange items in alphabetical order. Let us now use this method to arrange array elements in alphabetical order.
It results as:
Sorting array elements
The state names in alphabetical order are
How to reverse array elements?
Reversing an array elements mean to reverse the order of array elements. After reversing array elements, the last element becomes first element and first element becomes last element. This can be achieved with the help of built-in
The result becomes:
Reversing array elements
The state names in reverse order are
How to sort numeric array?
sort() method used above is helpful in sorting array alphabetically and does not produce desired results when it is used with numbers because the
sort() method converts numbers into strings which means 30 becomes “30” and 45 becomes “45”. To fix this problem, we can use compare formula in
sort() method as shown below.
Its output becomes:
The sorted array is 2,4,9,21,25,66,74
Now, let us see how does this sorting method with compare function works. In above example, we have to sort an array [2, 9, 4, 25, 74, 66, 21].
Let us suppose the first element is represented by a and the second element is being represented by b.
First, we will find the difference of a=2 and b=4 by using equation a-b which is in this case is 2-4=-2 which is less than 0. If we find the difference of first two numbers less than 0, then a becomes first and if the difference of these numbers is greater than 0, then b becomes first and if the difference is 0, then numbers will be unaltered and so on.