Sorting
Quick Sort
It’s generally an “in-place” algorithm, with the average time complexity of O(n log n).
Outline of the partition
method goes something like this:
Pick a pivot point.
Move all elements that are less than the pivot point to the left side of the partition.
Move all elements that are greater than the pivot point to the right side of the partition.
Return the index of the pivot point.
_________________
quickSort()
partition()
3-Way QuickSort
In 3 Way QuickSort, an array arr[l..r] is divided in 3 parts:
a) arr[l..i] elements less than pivot.
b) arr[i+1..j-1] elements equal to pivot.
c) arr[j..r] elements greater than pivot.
See this for implementation.
Quick Select
Quick Select is a selection algorithm to find the k-th smallest element in an unordered list.
The algorithm is similar to QuickSort. The difference is, instead of recurring for both sides (after finding pivot), it recurs only for the part that contains the k-th smallest element.
This reduces the expected complexity from O(n log n) to O(n), with a worst case of O(n^2).
Pseudo Code:
QuickSort vs MergeSort
Source: https://www.baeldung.com/java-quicksort
Let’s discuss in which cases we should choose QuickSort over MergeSort.
Although both Quicksort and Mergesort have an average time complexity of O(n log n), Quicksort is the preferred algorithm, as it has an _O(log(n)) _space complexity. Mergesort, on the other hand, requires _O(n) _extra storage, which makes it quite expensive for arrays.
Quicksort requires to access different indices for its operations, but this access is not directly possible in linked lists, as there are no continuous blocks; therefore to access an element we have to iterate through each node from the beginning of the linked list. Also, Mergesort is implemented without extra space for LinkedLists.
In such case, overhead increases for Quicksort and Mergesort is generally preferred.
Reference
Toptal: Sorting Algorithms Animations
Leetcode 排序类题目 排序算法总结: https://www.jianshu.com/p/fb3e38defec4
Last updated