In this article, I will be talking about quick sort & all the components that you need to know.

Quicksort is nothing but another algorithm to sort a list of items in ascending or descending order. To understand quick sort, we need to understand the following items:

  • pivot
  • how partition works
  • recursion within quick sort & the base case

Let’s start with pivot. What is pivot then?

Pivot is the element that will be used to divide the list of values less than pivot to the left(or the right, if we are sorting it the other direction) and values greater than the pivot to the right of the pivot.

Let’s say we have the following:

/* Example array: 4 1 5 2 10 8 6 3 */

	const array = [4,1,5,2,10,8,6,3];

	//the first element,4, or the last element,3, is commonly used as a pivot in quick sort. 

	//after partition:
	[?,?,3,?,?,?,?]
view raw
pivot.js hosted with ❤ by GitHub

If 3 is chosen as the pivot, it will always land at where it should be left after a partition. In this case, that would be the 2nd index of the array.

To further demonstrate how that would work, view the following illustration:

Image for post

On the illustration above, we have i, j, and the pivot. 4 is used as the pivot. i, initially, is set to -1. This indicates the number of elements we have that are less than the pivot. j, on the other hand, is used as an index to traverse through every element.

In partition, for every element j, if the pivot is great than arr[j], increment i and swap arr[i] and arr[j]. This will help put whatever element less than pivot on the left side of the array. J will increment regardless.

After the whole array is done, i equates to the number of elements that are less the pivot. Increment i by 1 and swap arr[i] with the pivot. Now the pivot is truly the dividing point between elements greater than it to the right and elements lesser than it to the left.

Afterward, quicksort will be called on the subarray to the left of the pivot and also to the right of the pivot. This process will repeat until there are no more subarrays to be sorted.

#sorting-algorithms #es6 #algorithms #javascript #web-development #algorithms

Explanation of Quick Sort
2.50 GEEK