Lecture
Implementing Quick Sort in Python
1. Pivot Selection and Partition
Select a pivot from the array and partition the array into two parts based on the pivot.
During this process, all elements smaller than the pivot are placed to the left, and elements larger are placed to the right.
Pivot Selection and Partition
pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot]
2. Recursive Sorting
Recursively sort the left and right sub-arrays.
Example of Recursive Sorting
return quick_sort(left) + middle + quick_sort(right)
Time Complexity
-
Worst-Case Time Complexity: O(n^2)- Occurs when pivot selection is unfortunate (e.g., always choosing the minimum or maximum value as the pivot). In this case, the array does not divide evenly and continues to be skewed to one side.
-
Best-Case Time Complexity: O(nlog n)- Applicable when the pivot consistently divides the array into two equal halves. Each division reduces the array size by half, resulting in logarithmic time complexity.
-
Average-Case Time Complexity: O(nlog n)- In most situations, Quick Sort has an average time complexity of nlog n, assuming that pivot selection is uniformly balanced.
Lessons in this chapter · Practical Python Algorithms
- 1. Advanced Python Algorithms
- 2. What is a Recursive Call?
- 3. Implementing Fibonacci Sequence with Recursive Function
- 4. Fill-in-the-blank quiz
- 5. Coding Quiz - Fibonacci Sequence
- 6. Dynamic Programming and Divide and Conquer
- 7. Implementing Dynamic Programming in Python
- 8. Multiple-choice quiz
- 9. Coding Quiz - Make One
- 10. What is Merge Sort?
- 11. Implementing Merge Sort
- 12. Multiple-choice quiz
- 13. Coding Quiz - Sort a List Using Merge Sort
- 14. What is Quick Sort?
- 15. Implementing Quick Sort in Python
- 16. Multiple-choice quiz
- 17. Coding Quiz - Sort a List Using Quick Sort
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help