Quicksort is an algorithm based on divide and conquer approach in which the array is split into subarrays and these sub-arrays are recursively called to sort the elements.

How Quicksort Works?

Step1: A pivot element is chosen from the array. You can choose any element from the array as the pivot element. Here, we have taken the rightmost (i.e. the last element) of the array as the pivot element.

Step2: The elements smaller than the pivot element are put on the left and the elements greater than the pivot element are put on the right.

The above arrangement is achieved by the following steps.

a) A pointer is fixed at the pivot element. The pivot element is compared with the elements beginning from the first index. If the element greater than the pivot element is reached, a second pointer is set for that element.

b) Now, the pivot element is compared with the other elements (a third pointer). If an element smaller than the pivot element is reached, the smaller element is swapped with the greater element found earlier.

c) The process goes on until the second last element is reached.
Finally, the pivot element is swapped with the second pointer.

d) Now the left and right subparts of this pivot element are taken for further processing in the steps below.

Step3: Pivot elements are again chosen for the left and the right sub-parts separately. Within these sub-parts, the pivot elements are placed at their right position. Then, step 2 is repeated.

Step4: The sub-parts are again divided into smaller sub-parts until each subpart is formed of a single element.

Step5: At this point, the array is already sorted.

Output