Killersites Forums

# Newb question on the array.sort function

## Recommended Posts

I'm trying to grasp what's going on "under the hood" of the array.sort function in Javascript. Let's use the following example:

```var myarray=[25, 8, 7, 41]
myarray.sort(function(a,{return a - b}) //Array now becomes [7, 8, 25, 41]
```

I know it might sound silly, but since the function takes two values -- a and b -- exactly which two values are being compared at any given time in the logic??

I understand the sorting "rules" in terms of <0, 0, and >0 re: sort order. I'm just wondering what, exactly is going on in the sort process in Javascript at each step of the function?

In other words, is the first step to set parameter a to 25 and b to 8 and do the subtraction, then 25 - 7, then 25 - 41? This is what is seemingly never explained in the examples I see. Is it a loop that's being performed with every possible iteration of elements in the array subtracting from each other in this case?

I'm wondering what is assigned to "a" and what to "b" at any given time while the function processes.

(I don't know why "B" shows up in the code capitalized - I tried to make it lower-case but it wouldn't take.)

##### Share on other sites

Does the explanation here help at all?

http://www.javascriptkit.com/javatutors/arraysort.shtml

Hi Ben,

That's actually where I got the code, lol. I guess I'm asking this (and don't ask me why -- it's just something that will help me visualize it):

In the sort example I used, say someone asked you, Ben, to write out step by step exactly what was happening as the function did it's math and comparison thing; the steps you don't SEE happening . What would you write?

I'm thinking of something along the lines of:

1. a = 28 b=8 28 minus 8 means value a is larger than 0, and hence to the right of value b in the ascending sort order.

2. a = ?? b=?? a minus b = ??

3. a = ?? b=?? a minus b = ??

etc.

I guess I'm asking if anyone knows the exact process of what values are being compared to what other values. Since there are only two values that can be compared at any given instant, what values are they and in what order at any moment in time in the function processing? Does it depend on where they appear in the array? Make sense?

##### Share on other sites

This modified code may be helpful: it shows the initial and final arrays, as well as the values and results at each step of the function:

```<script>

var x = 1;
var myarray=[25, 8, 7, 41];

// display initial array
document.write("Initial Array:<br/>");
for(var i=0;i<myarray.length;i++){
document.write("<b>myarray["+i+"] is </b>=>"+myarray[i]+"<br>");
}
document.write("<br/><br/>");

myarray.sort(

function(a,
{
document.write("Step " + x + " - a: " + a + " b: " + b + " - result: " + (a - );
document.write("<br/>");
x++;

return a - b;
}

);

// display final array
document.write("<br/><br/>");
document.write("Final Array:<br/>");
for(var i=0;i<myarray.length;i++){
document.write("<b>myarray["+i+"] is </b>=>"+myarray[i]+"<br>");
}

</script>```

##### Share on other sites

This modified code may be helpful: it shows the initial and final arrays, as well as the values and results at each step of the function:

```<script>

var x = 1;
var myarray=[25, 8, 7, 41];

// display initial array
document.write("Initial Array:<br/>");
for(var i=0;i<myarray.length;i++){
document.write("<b>myarray["+i+"] is </b>=>"+myarray[i]+"<br>");
}
document.write("<br/><br/>");

myarray.sort(

function(a,
{
document.write("Step " + x + " - a: " + a + " b: " + b + " - result: " + (a - );
document.write("<br/>");
x++;

return a - b;
}

);

// display final array
document.write("<br/><br/>");
document.write("Final Array:<br/>");
for(var i=0;i<myarray.length;i++){
document.write("<b>myarray["+i+"] is </b>=>"+myarray[i]+"<br>");
}

</script>```

Hi Ben,

Thanks for doing that. It was both helpful yet still a little mysterious when I see the sequence play out. Here's how the code runs:

Initial Array:

myarray[0] is =>25

myarray[1] is =>8

myarray[2] is =>7

myarray[3] is =>41

Step 1 - a: 25 b: 8 - result: 17

Step 2 - a: 25 b: 7 - result: 18

Step 3 - a: 8 b: 7 - result: 1

Step 4 - a: 25 b: 41 - result: -16

Final Array:

myarray[0] is =>7

myarray[1] is =>8

myarray[2] is =>25

myarray[3] is =>41

Notice "Step 3", where all of the sudden the value of a: changes to 8 vs its value of 25 in all the other steps. I'm still curious how/why that occurs. Sorry if I'm belaboring this, and I do appreciate the work you put into writing out the code!

##### Share on other sites

My understanding is that when you are dealing with this array:

var myarray=[25, 8, 7, 41];

the process goes something like this:

-- compare 25 (a) and 8 (b ). Since b is smaller, switch a and b within the array so it becomes [8, 25, 7, 41]

-- compare the next two values: 25 (a) and 7 (b ). Since 7 is smaller than 25, switch.

-- etc.

However, there must be something slightly more complicated going on, since if it's just comparing two values and looping, it should result in [8, 7, 25, 41]. Just comparing one value with the next and switching them based on the values won't necessarily generate a sorted array. There must be something slightly more going on that ensures that they are all compared correctly -- perhaps recursion? I don't fully understand it myself, and I'm not really finding anything online so far that fully explains it.

##### Share on other sites

My understanding is that when you are dealing with this array:

var myarray=[25, 8, 7, 41];

the process goes something like this:

-- compare 25 (a) and 8 (b ). Since b is smaller, switch a and b within the array so it becomes [8, 25, 7, 41]

-- compare the next two values: 25 (a) and 7 (b ). Since 7 is smaller than 25, switch.

-- etc.

However, there must be something slightly more complicated going on, since if it's just comparing two values and looping, it should result in [8, 7, 25, 41]. Just comparing one value with the next and switching them based on the values won't necessarily generate a sorted array. There must be something slightly more going on that ensures that they are all compared correctly -- perhaps recursion? I don't fully understand it myself, and I'm not really finding anything online so far that fully explains it.

Well, thanks again, Ben. What I'm happiest about is that I wasn't missing something totally obvious, and that there must be something more complicated, as you say, occuring in the process.

As you can imagine, I was the kid who incessantly asked "but why?" to everything I was told by parents, teachers, lol. It just bothers me when there's (sometimes) no full explanation of the process, but we're just expected to live with "hey, it works -- that's all you need to know!" These kinds of things are stumbling blocks for me, unfortunately, when I'm undertaking something new in life such as learning coding.

I appreciate the assist.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.