DEV Community

Discussion on: Quicksort In Javascript

Collapse
 
faiwer profile image
Stepan Zubashev

Unfortunately in real world you also need:

  • get rid of ...
  • mutate one array, instead of pushing sorted items in a new array

Otherwise it can be shown as an example of a binary algorithm, but actually it's so strongly slow that even doesn't make any sense. Just because ... has O(n) where n is .length and you repeat it again and again. Whereas mutating an existing array you will just sometimes shift elements.

Array push has O(1), but sometimes it costs O(n). Becase it's like a rubber. It has some extra space at the end and when this space ran out it just copies everything to a new array with bigger extra space.

In case when you need to create a new sorted array you can just do it at the very beginning. I mean create a clone-array and then mutate it.

Collapse
 
ogzhanolguncu profile image
Oğuzhan Olguncu • Edited

I used this example to teach the idea of quicksorting and recursion. This is not a real-world example. By the way, you can easily get rid of shift() using first item as an index arr[0] and start iterating by staring from index 1. And I don't think ... gives you any side effects.

But you might be right about push(). If you truly improve the performance of your sort, you should really focus on choosing better pivots I picked the first for simplicity. Maybe try using Median of three(First,Middle,Last) or maybe median of three random elements to avoid O(n2).

So anyway, I'm open for improvements to ease out the learning curve of this algorithm.

Collapse
 
faiwer profile image
Stepan Zubashev

... doesn't give you any side-effect, you're right. It's FP pure. But it is copying the whole array every time :) That's where the problem is.

If you truly improve the performance of your sort, you should really focus on choosing better pivots I picked the first for simplicity

I think you may even set pivot equal 0 each iteration and even then it would be faster than version with ... :)

... ruins this algorithm. Most of algorithms have to be impure to be useful.
So you can dramatically improve it by getting rid of excess copies. I think it'd be better even in educational point of view