Possible Duplicate:
How does Javascript's sort() work?
var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return b - a})// for descending order
In a callback function, what does a
and b
variables refer to??
why and how does b-a
exactly make array in descending order??
Given a sorted array, remove all the duplicates from the array in-place such that each element appears only once, and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Like counting sort, this is an efficient variant if there are many duplicate values: selection sort does one pass through the remaining items for each item moved, while Bingo sort does one pass for each value.
This algorithm may also be used to eliminate duplicate keys, by replacing the Count array with a bit vector that stores a one for a key that is present in the input and a zero for a key that is not present.
a
and b
are two of the values in the array, that you compare so Javascript can sort them.
The function is called lots of times to determine where each element in the array is compared to all the others. The exact number of times the function is called depends on the number of elements in the array and their original order.
You need to return 0 if the two elements are equal, a negative number if a
should be before b
and a positive number if b
should be before a
.
The sort function has internal sorting algorithm. You just provide a way for the algorithm to determine, given two members of the array, which one of them is greater ( that is the purpose of the b-a
. ) Using this, the algorithm will be able to place the elements in the necessary order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With