1

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.

5
  • 1
    It depends on the internal implementation of sort. It's probably some variation of heapsort or quicksort.
    – Ted Hopp
    Commented Feb 7, 2013 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
    Commented Feb 7, 2013 at 9:00
  • yes, I just put few lines of output
    – Bhupi
    Commented Feb 7, 2013 at 9:03
  • possible duplicate of Javascript Array.sort implementation? Commented Feb 7, 2013 at 9:05
  • possible duplicate of How does Javascript's sort() work? Commented Feb 7, 2013 at 9:06

1 Answer 1

2

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?

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.