Partition Algorithm
The purpose of the partition algorithm in Quickselectis to rearrange the elements of an array such that all elements less than a chosen pivot element are placed before it, and all elements greater than the pivot are placed after it.
The following is a linear-time implementation of the partition algorithm:
In this algorithm, we initialize three empty lists: smaller
, equal
, and larger
. We choose the pivot element v
from the array A
at index p
. Then, we iterate through all the elements in A
and place them in the appropriate list based on their relationship with the pivot.
After the iteration, we know the sizes of the smaller
and equal
lists, which correspond to the number of elements smaller than and equal to the pivot, respectively. We overwrite the elements of A
in three steps: first, with the elements in smaller
, then with the elements in equal
, and finally with the elements in larger
. Finally, we return the index i
which represents the index of the pivot after partitioning.
Partition algorithm used in Quickselect and Quick Sort.
Optional - In-Place partition (Hoare)
- Is Hoare’s in-place partition algorithm stable?
- False
- Suppose part of my array has something like and Hoare’s partition chose 2nd 7. First, it will move that 7 to the very end. At the end, we will place this second 7 into right place, but this will for sure will be left to first 7. Hence, this is not stable. Hope this helps!