Quick sort algorithm
Aya Bouchiha
Posted on June 24, 2021
Definition of quicksort
Quicksort is a type of Divide and Conquer algorithm like merge sort, it works by choosing an element as a pivot from the giving array, and appending the greater elements to the selected pivot, and shifting the smaller elements before it.
Time and Space complexity
The space complexity of quicksort is O(log n)
best-case | average case | worst-case |
---|---|---|
O(n log n) | O(n log n) | O(n^2) when the list is already sorted, or the pivot is min or max value of the giving list |
Implementation of quick sort using python
def QuickSortAlgorithm(arr: list) -> list:
"""
[ name ] => Quick Sort
[ type ] => Sorting algorithms
[ time complexity ] => (
1. best case: O(n log n)
2. average case: O(n log n)
3. worst case: O(n^2) { when the pivot is the (min or max) value of the giving list, or the list is already sorted }
)
[ space complexity ] => O(log n)
[params] => (
arr {list} list to sort
)
[return] => {list} sorted list
"""
# size of array
n = len(arr)
if n <= 1:
return arr
# pivote = arr[mid]
pivot = arr[n // 2]
smallerThanPivot = []
greaterThanPivot = []
for i in range(len(arr)):
# do not append pivot to (greaterThanPivot) => continue
if arr[i] == pivot:
continue
# if the element is greater than or equal pivot
if arr[i] >= pivot:
# append the element that is greater than pivot to greaterThanPivot array
greaterThanPivot.append(arr[i])
else:
# if the element is smaller than pivot append it to smallerThanPivot
smallerThanPivot.append(arr[i])
return QuickSortAlgorithm(smallerThanPivot) + [pivot] + QuickSortAlgorithm(greaterThanPivot)
References and useful resources
- https://www.youtube.com/watch?v=8hly31xKli0&t=16878s
- https://www.geeksforgeeks.org/when-does-the-worst-case-of-quicksort-occur/
- https://en.wikipedia.org/wiki/Quicksort
- https://www.youtube.com/watch?v=PgBzjlCcFvc
- https://www.youtube.com/watch?v=7h1s2SojIRw
- https://www.youtube.com/watch?v=0SkOjNaO1XY
#day_12
💖 💪 🙅 🚩
Aya Bouchiha
Posted on June 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.