An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
June 24, 2021 08:45 pm GMT
Original Link: https://dev.to/ayabouchiha/quick-sort-algorithm-1k72
Quick sort algorithm
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
Original Link: https://dev.to/ayabouchiha/quick-sort-algorithm-1k72
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To