Sort Function in javascript

Viewed 40

I want to know how the sort function in js works behind the scenes. I am passing an array to the function, it's sorting the array correctly but when I print the values of a and b I am getting confused that how js sorted the array.

My confusions:

  1. Why it's taking so many iterations to perform though it could be done in very less iterations.

  2. How js is choosing the values from the given array to pass as arguments(a and b).

  3. What's the method of sorting.

  4. Why there is same value for a and b in the multiple iterations.

Here is my code:

const points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b) {
  document.write("a:" + a + " b:" + b + "<br>");
  return a - b
});

document.write(points);

and my output:

a:100 b:40
a:1 b:100
a:1 b:100
a:1 b:40
a:5 b:40
a:5 b:1
a:25 b:40
a:25 b:5
a:10 b:25
a:10 b:5
1,5,10,25,40,100
0 Answers
Related