Question: Does the choice of the pivot affect the running time of quick sort? Why or why not? It would help if you could provide examples or illustrations.

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter10: Classes And Data Abstraction
Section: Chapter Questions
Problem 23PE
icon
Related questions
Question

Big-O Solving (PYTHON)

Question: Does the choice of the pivot affect the running time of quick sort? Why or why not? It would help if you could provide examples or illustrations.

Given ONLY:

Quick Sort is another sorting algorithm that follows a divide-and-conquer approach. The algorithm can be summarized in 3 steps:

  1. pivot element is chosen, usually the first element.
  2. All elements smaller than the pivot are placed to the left of the pivot. This creates 2 partitions, elements greater than the pivot and elements less than the pivot.
  3. The 2 partitions are sorted using Quick Sort.

Sample code in python3:

   def quick_sort(arr):
     def quick_sort_r(arr, start, end):
       if end - start < 2:
         # single element base case
         return

       # choose a pivot
       pivot = start # you may choose other elements
       store = pivot+1 # index to store less than elements

       # for all elements after the pivot
       for i in range(pivot+1, end):
         if arr[i] < arr[pivot]:
           # if element is less than pivot
           arr[i], arr[store] = arr[store], arr[i] # swap
           store += 1 # increment store index

       # swap pivot with last element in less than partition
       arr[pivot], arr[store-1] = arr[store-1], arr[pivot]
       pivot = store-1 # new pivot index

       # Recursive Calls
       quick_sort_r(arr, start, pivot) # sort less than partition
       quick_sort_r(arr, pivot+1, end) # sort greater than partition
       return
   quick_sort_r(arr, 0, len(arr))

Expert Solution
steps

Step by step

Solved in 2 steps

Blurred answer
Knowledge Booster
Mergesort
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning
EBK JAVA PROGRAMMING
EBK JAVA PROGRAMMING
Computer Science
ISBN:
9781337671385
Author:
FARRELL
Publisher:
CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
Programming Logic & Design Comprehensive
Computer Science
ISBN:
9781337669405
Author:
FARRELL
Publisher:
Cengage