Sort using quick sort algorithm 36, 25, 32, 5, 8, 38, 47, 95


Q.) Sort using quick sort algorithm 36, 25, 32, 5, 8, 38, 47, 95

Subject: Data Structures - II

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 of Ο(n2), where n is the number of items.

Here is a step-by-step approach to sort the given array [36, 25, 32, 5, 8, 38, 47, 95] using the quick sort algorithm.

  1. Step 1: Choose the highest index value as pivot (pivot = 95)

  2. Step 2: Take two variables to point left and right of the list excluding pivot

    • left_pointer = 0
    • right_pointer = 7 (excluding pivot)
  3. Step 3: While the value at the left is less than pivot move right

    • left_pointer = 4 (value at index 4 is 8)
  4. Step 4: While the value at the right is greater than the pivot move left

    • right_pointer = 0 (value at index 0 is 36)
  5. Step 5: If the step 3 and step 4 does not match swap left_pointer and right_pointer

    • After swapping, the array becomes [8, 25, 32, 5, 36, 38, 47, 95]
  6. Step 6: If the left_pointer and right_pointer cross, swap the right_pointer with pivot

    • After swapping, the array becomes [8, 25, 32, 5, 36, 38, 47, 95]
  7. Step 7: Now, elements at left of pivot are less than pivot and elements at right are greater than pivot. So, divide the list into two parts, sort them separately by repeating step 1 to step 6.

After the first pass, the array becomes [8, 25, 32, 5, 36, 38, 47, 95]. Repeat the steps for the two sub-arrays [8, 25, 32, 5, 36] and [38, 47, 95] separately.

After the second pass, the array becomes [5, 8, 25, 32, 36, 38, 47, 95].

So, the sorted array is [5, 8, 25, 32, 36, 38, 47, 95].

This is how quick sort works. It's a divide and conquer algorithm. It's efficient for large data sets and its time complexity is O(n log n) in the best case and O(n^2) in the worst case when the pivot elements are unbalanced.