-
Hajipur, Bihar, 844101
Quick Sort is a highly efficient divide-and-conquer sorting algorithm.
It works by selecting a pivot element and partitioning the array around it — smaller values to the left, larger to the right.
Pick a pivot element
Partition the array:
Elements less than pivot → left side
Elements greater than pivot → right side
Recursively apply the above steps on left and right subarrays
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
numbers = [10, 7, 8, 9, 1, 5]
sorted_list = quick_sort(numbers)
print("Sorted array:", sorted_list)
✅ Output:
Sorted array: [1, 5, 7, 8, 9, 10]
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort_inplace(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quick_sort_inplace(arr, low, pi - 1)
quick_sort_inplace(arr, pi + 1, high)
Case | Time |
---|---|
Best Case | O(n log n) |
Average | O(n log n) |
Worst Case | O(n²) |
Space | O(log n) |
Worst-case occurs when the smallest or largest element is always chosen as pivot.
Large datasets
When average performance is more important than worst-case
Faster than Merge/Insertion in most real-world scenarios
Q1. Write a Python program to sort the list [3, 7, 2, 9, 1]
using quick sort.
Q2. Write a Python program to modify quick sort to use the middle element as the pivot.
Q3. Write a Python program to sort a list of strings alphabetically using quick sort.
Q4. Write a Python program to track and print the number of recursive calls made during quick sort.
Q5. Write a Python program to sort a list that contains duplicate values using quick sort.
Q6. Write a Python program to accept a list of numbers from user input and sort it using quick sort.
Q7. Write a Python program to print the array after each partition step in quick sort.
Q8. Write a Python program to implement in-place quick sort (without creating new sublists).
Q9. Write a Python program to count and display the total number of comparisons made during quick sort.
Q10. Write a Python program to compare the execution time of quick sort and merge sort on a list of 1,000 random numbers.
Q1: What is the key concept of quick sort?
Q2: What is a pivot in quick sort?
Q3: Time complexity in best/average case?
Q4: Quick sort worst-case time?
Q5: What happens during partition?
Q6: Is Quick Sort recursive?
Q7: Can Quick Sort be used to sort strings?
Q8: What is the base condition in Quick Sort?
Q9: Which version of Quick Sort is more memory efficient?
Q10: What kind of sorting algorithm is Quick Sort?