2

Okay, so i understand how to sort numbers from big to small or small to big. what I don't understand is how it actually is done by javascript. can somebody walk me through, step by step how javascript is sorting the following array? I know how to use it, I need to understand it.

var arr = [3, 2, 4, 5, 1]

function sorter(a, b) {
  return a - b;
}
arr.sort(sorter)

can you show me which number is for a, and which is for b, and how does it iterate through the rest of the array. For instance, 3 - 2 is 1, so it would switch 2 to an index lower than 3, how does this continue for this entire array? I want to understand why this works, not just use it blindly. Thanks!!

David Zalk
  • 29
  • 5
  • 2
    That is not specified and implementation-dependant. It also depends on the size of the array. – str Nov 02 '18 at 13:10
  • 2
    Possible duplicate of [Javascript native sort method code](https://stackoverflow.com/questions/6640347/javascript-native-sort-method-code) – qiAlex Nov 02 '18 at 13:12
  • 1
    "[How to sort your socks using Javascript](https://www.youtube.com/watch?v=-6DTgFnvnXI)" by Claudia Hernández is a good introduction into the topic. – str Nov 02 '18 at 13:13

1 Answers1

0

can you show me which number is for a, and which is for b, and how does it iterate through the rest of the array.

it doesn't matter; and it is not specified.

Browsers can implement whatever sorting algorithm they want. All that's defined is that they call the function with two different entries in the Array (different in terms of index, not as different values) and your function should return

  • 0 if these values are identical in terms of order
  • <0 if the first argument should be before the second argument
  • >0 if the first argument should be after the second argument

You may want to check out some sorting algorithms

Thomas
  • 11,958
  • 1
  • 14
  • 23
  • i get how the numbers are arranged, Im asking what index is a, and what is b & how it loops through the array. Is it array[0] = a, array[1] = b, than array[1] = a, array[2] = b, and so on until end of array? After one iteration it would be [4, 3, 2, 1, 5]. Does it keep cycling back to the start of the array when it reaches the end? Eventually the array sorts to [1, 2, 3, 4, 5] following this logic. Is my explanation correct that it loops in this way? Also, what tells the comparison to stop looping through the array once it is sorted? What is the condition that tells function to stop sorting? – David Zalk Nov 02 '18 at 21:48