Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does array.sort work? [duplicate]

Tags:

javascript

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??

like image 387
DrStrangeLove Avatar asked Jul 09 '11 23:07

DrStrangeLove


People also ask

Does array sorted remove duplicates?

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.

Does selection sort work with duplicates?

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.

Can counting sort handle duplicates?

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.


2 Answers

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.

like image 119
lonesomeday Avatar answered Nov 11 '22 14:11

lonesomeday


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.

like image 26
manojlds Avatar answered Nov 11 '22 13:11

manojlds