Explain Quick sort? Sort the following elements using Quick sort: 32, 23, 56, 78, 12, 66, 37, 93, 29, 80


Q.) Explain Quick sort? Sort the following elements using Quick sort: 32, 23, 56, 78, 12, 66, 37, 93, 29, 80

Subject: Data Structures

Quick sort is a highly efficient sorting algorithm and is based on the partitioning of an array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value. Quick sort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case time complexity are O(nLogn) and image.pngO(n2), respectively.

Here are the steps to perform Quick sort:

  1. Choose an element, called pivot, from the list. Generally pivot can be the middle index element.
  2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively apply the above steps to the sub-list of elements with smaller values and separately to the sub-list of elements with greater values.

Let's sort the given list: 32, 23, 56, 78, 12, 66, 37, 93, 29, 80

We'll choose the first element as the pivot for simplicity.

  1. Pivot = 32. Partition the list into elements < 32, 32, elements > 32. We get: 23, 12, 29, 32, 56, 78, 66, 37, 93, 80
  2. We now sort the sub-lists [23, 12, 29] and [56, 78, 66, 37, 93, 80] using the same approach.
  3. For [23, 12, 29], Pivot = 23. We get: 12, 23, 29
  4. For [56, 78, 66, 37, 93, 80], Pivot = 56. We get: 37, 56, 78, 66, 93, 80
  5. Repeat the process for [37] and [78, 66, 93, 80]. Since [37] has only one element, it is already sorted.
  6. For [78, 66, 93, 80], Pivot = 78. We get: 66, 78, 93, 80
  7. Repeat the process for [66] and [93, 80]. Both [66] and [93, 80] are already sorted as they have less than or equal to 2 elements.

So, the final sorted list is: 12, 23, 29, 32, 37, 56, 66, 78, 80, 93

Here is the step by step process:

Step List
0 32, 23, 56, 78, 12, 66, 37, 93, 29, 80
1 23, 12, 29, 32, 56, 78, 66, 37, 93, 80
2 12, 23, 29, 32, 56, 78, 66, 37, 93, 80
3 12, 23, 29, 32, 37, 56, 78, 66, 93, 80
4 12, 23, 29, 32, 37, 56, 66, 78, 93, 80
5 12, 23, 29, 32, 37, 56, 66, 78, 80, 93

This is a simple demonstration of Quick sort. In practice, the pivot selection and partitioning steps can be done in several different ways.