20-4. Quick Sort

Quick sort is a sorting algorithm that utilizes the divide and conquer approach.

The quick sort algorithm operates in the following manner: it chooses a pivot element from the list. Then, it partitions the list into two segments, ensuring that all elements in the first segment are either less than or equal to the pivot, while all elements in the second segment are greater than the pivot. Apply the quick sort algorithm recursively to both the first and second segments.

1. How it works?

Let's say we have a list of elements, and we're attempting to sort the elements in ascending order.

 

a. Quick sort of all elements:

Firstly, apply the quick sort algorithm to all elements in the list.

 

b. Quick sort of the first partition:

Next, apply the quick sort algorithm to the first partition in the list.

 

c. Quick sort of the second partition:

Next, apply the quick sort algorithm to the second partition in the list.

 

d. Quick sort of the first partition of the second partition:

 

e. Quick sort of the second partition of the second partition:

 

2. Quick Sort Implementation

Output:

[2, 3, 5, 6, 7, 8, 9, 10]

 

3. Time Complexity

In the worst-case scenario, each time the pivot is chosen, it divides the list into one large sublist and another empty sublist. The size of the larger sublist is one less than the size of the previous sublist. Thus, the complexity of the quick sort algorithm in this scenario is O(n2).

In the best case, each time the pivot is selected, it divides the array into two approximately equal-sized parts. Let T(n) denote the time required for sorting an array of  elements using quicksort.

Hence,

 

The complexity is O(n log n).