Quick Sort (JavaScript)

Method #1: For loop

In this method, we make our pivot our right-most element (so as to make the for loop more readable, as it can still go left-to-right). Then we loop through all of the elements in the array, and move those lower than the pivot to the left hand side, and those greater than it to the right hand side. Finally, we place the pivot in the middle of all these numbers (technically, we swap it for the lowest number that is greater than the pivot), and we have then found the correct placement for the pivot.

Method #2: While

In this method, we make our pivot the left-most element. Next we place markers at the next element in the array, and the final element of the array. Now, we move the left-marker right until we find a value that is greater than the pivot, and we move the right-marker left until we find a value that is lower than the pivot. In other words, we constrict the window of observation until we find numbers that belong on the opposite sides. Then we swap these values, so that they are now on the correct sides, and then continue until our markers meet. Finally, we place the pivot in the middle of all these numbers, and we have then found the correct placement for the pivot.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Duncan McArdle

Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.