Difficulty in fully understanding the algorithm of Javascript sort function

const numbers = [74, 18, 10, 5, 84, 24, 105]
numbers.sort(compareFunction)
console.log(numbers)
function compareFunction(a, b) {
return a - b
}

The above is sorting the array as a numerically ascending order, not as a string, but how does it do unless I understand I won’t be able to apply that in other situations in the future?

In total there are 7 elements in the array, holding positions from 0 - 6.

  1. element position at “0” will be compared to the remaining, 1-6?
  2. Once Point No 1 is accomplished then the element at position 1 will be compared to the remaining elements occupying positions at JS index between 2-6? and so on…
  3. Finally sorted array is delivered.

Edit: It appears the sort algorithm used is browser dependent. So the following bubblesort implementation is wrong.

I think this is about right.

Adjacent indexes are checked swapping values accordingly. This may take numerous iterations of the array to complete. The check will be complete when a full iteration of the array is completed and no swapping has occurred.

[A,  B,  C,  D]

Compares
A, B
B, C,
C, D

Example comparing a < b with an array [4, 2, 5, 1]

First iteration

4, 2 → 2, 4 // swapped
4, 5 → 4, 5 // not swapped
5, 1 → 1, 5 // swapped

-> [2, 4, 1, 5]

Second iteration

2, 4 → 2, 4 // not swapped
4, 1 → 1, 4 // swapped
4, 5 → 4, 5 // not swapped

-> [2, 1, 4, 5]

Third iteration

2, 1 →  1, 2 // swapped
2, 4 →  2, 4 // not swapped
4, 5 →  4, 5 // not swapped

-> [1, 2, 4, 5]

Final iteration

1, 2 →  1, 2 // not swapped
2, 4 →  2, 4 // not swapped
4, 5 →  4, 5 // not swapped

-> [1, 2, 4, 5]

No items were swapped, so finish!

3 Likes

You cannot know which sort algorithm your JavaScript is using. In fact this can vary from browser to browser and from JavaScript version to to version.

In fact it will never be the method rpg has posted as this is a very slow one.

You can start improving your knowledge by reading this article on wiki

3 Likes

Here’s more than you ever wanted to know on the subject.

TL;DR is that Firefox uses merge sort and with Chrome it kinda depends.

2 Likes

@Thallius It was my understanding that JS used Bubblesort, which yes as you pointed out is not the most efficient method for large arrays. It appears reading James’ link that I was wrong.

1 Like

Thanks.

1 Like