Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This might be a very basic question but I am not able to understand this so please help me to understand how the Javascript's Array.sort() function is working here. I need to understand the dry run of the code:

var x = new Array(5,4,3,78,7,66,5,444,7,8,9,33,4,5,666,1);
console.log("Before = "+ x);
x.sort(
function(a, b){
    var m = a-b;
        console.log(a+" - "+b+" = "+m);
        return m;
    }
);
console.log("After = "+ x);

When I run the above code I found the output as follows: (Here are the few lines of output)

5 - 1 = 4 
1 - 7 = -6 
5 - 7 = -2 
3 - 5 = -2 
78 - 5 = 73 
666 - 5 = 661
etc....

And finally it printed the sorted array in ascending order:

After = 1,3,4,4,5,5,5,7,7,8,9,33,66,78,444,666 

Please let me know how it is picking up the values for "a" and "b" and how it is doing all operation.

share|improve this question
1  
It depends on the internal implementation of sort. It's probably some variation of heapsort or quicksort. –  Ted Hopp Feb 7 at 8:58
 
Your example is a bit misleading. The output you get is much, much longer than what you've posted. The full output correctly shows it comparing each number to each other number to determine the order they should be in. –  Jamiec Feb 7 at 9:00
 
yes, I just put few lines of output –  Bhupi Feb 7 at 9:03
 
possible duplicate of Javascript Array.sort implementation? –  Jan Dvorak Feb 7 at 9:05
 
possible duplicate of How does Javascript's sort() work? –  Sudhir Feb 7 at 9:06
add comment

1 Answer

There is a wide range of sort algorithms, but all (probably just most) need a way to compare two elements.

Compare functions in most languages work like this. When the return Value is positive, the second value is smaller and when the return value is negative the first value is smaller. If it is zero, they are the same.

Which actual sort algorithm Javascript uses might vary from implementation to implementation and it could probably use multiple different algorithms in one implementation or even one sort.

Also see Javascript Array.sort implementation?

share|improve this answer
 
This is not answering OP's question, which is how the algorithm is picking which values to test. –  Ted Hopp Feb 7 at 8:59
 
@TedHopp - I disagree. I think this perfectly answers the OP's question (both before and after the recent edit!) –  Jamiec Feb 7 at 9:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.