Sorting Algorithms with Javascript (Part 1)

Kinyanjui Wangonya on October 30, 2018

I've been learning a lot about data structures and algorithms lately and I've noticed in my reading that there aren't a lot of examples showing imp... [Read Full]
markdown guide

Hello there! First let me thank you for the article, it helped me a lot. As I was developing an insertion sort I came across your code and used it, although you have a litle mistake I ended up finding.

instead of:
if (list[i] > list[j-1] && list[i] < list[j])

you should have (= is missing on second validation):
if (list[i] > list[j-1] && list[i] =< list[j])

Otherwise, it wont sort. Once again, thank you!


Hey there! I'm glad you found it helpful. Thanks for that 😄.

The code seems to work just fine with the test list provided though. Would you mind explaining why the = is necessary? Or maybe share the list you tested the code with so I can also try it.

Ps: The = should be on the other side of the < in your example though, like so: if (list[i] > list[j-1] && list[i] <= list[j]) 🙂


Hey Kinyanjui, thanks again for the post! Super helpful!

Just hoping on to this, I noticed an issue with the same line of code where if a list has two elements with the same value it won't sort it properly. i.e. [4, 2, 3, 2, 1, 5] gives [ 1, 2, 3, 4, 2, 5 ] as a result.

Adding an = sign to the first argument makes all the difference! if (list[i] >= list[j-1] && list[i] < list[j]). It now returns [ 1, 2, 2, 3, 4, 5 ] :)

Thanks Lynn. I've edited the code to include your fix.


Hello guy ! Nice post !

What is the faster sort algorithm ? Is it depends of number of elements ?


Thanks for reading!

In this case, Merge sort is the faster of the three with time complexity O(nlogn). Time complexity (the estimated time taken by running an algorithm) is measured by how many operations are executed so yes, the number of elements will matter, but not as much as the order of the elements:

  • Worst-case time complexity (input elements in reversed order)
  • Best-case time complexity (already sorted)
  • Average-case time complexity (elements in random order)

Hey, nice overview. One thing though. Merge sort is also comparison based. To sort in the end, you always compare two elements.


Nice Article. Thanks for taking the time to write this :)


Thanks for taking the time to read Aditya :)

code of conduct - report abuse