Build a max-heap, then repeatedly swap its root with the last element of the active prefix, shrink that prefix and restore heap order by heapify down. A zero-based implementation is
for i = floor(n/2)-1,...,0:
siftDown(A,i,n)
for end = n-1,...,1:
swap A[0],A[end]
siftDown(A,0,end)siftDown(A,i,end) repeatedly exchanges entry i with its larger child while the child lies below end and has a larger key. The suffix beyond end is already sorted and never touched again. For the specified input, key stages of heapsort areThe final array is . Bottom-up construction takes time because there are progressively fewer nodes at each greater subtree height; the extractions give worst-case time and constant auxiliary storage for iterative sifting.
A deterministic comparison sort on distinct keys must distinguish possible initial orders. Its binary comparison decision tree therefore has at least leaves: a leaf fixes one output ordering and cannot be correct for two different strict orders of the original records.
A binary tree of height has at most leaves, henceThis is the comparison sorting lower bound on the worst-case number of comparisons. Distinct keys have only two possible comparison outcomes, even if an implementation's comparator also supports equality. Algorithms exploiting numeric key values, such as counting sort, fall outside this model.
The printed split uses while naming the current length . For the intended stooge sort, read that split as at every recursive call. Keeping one fixed original instead is not the standard algorithm and does not generally sort correctly.
The three recursive calls then each have length , and all other work is constant. ThusA version of the master theorem sufficient here states: if with constants , fixed-size base cases and for some , then , provided the recursive sizes shrink above the base threshold. Apply it with to obtainThe rounded size is important for correctness; it does not change this asymptotic exponent.
Prefer the alternatives for large unrestricted arrays. Merge sort and heapsort have worst-case time, while insertion sort has worst-case time and can be much faster on nearly sorted data. The intended stooge sort has worst-case , so even insertion sort has the better worst-case exponent.
The first two give the stronger general asymptotic guarantee. Choices between them can depend on storage and stable sorting requirements; these considerations do not rescue Stooge sort's much larger work count.
No: Stooge sort is not stable. Give equal keys distinct record identities and start withThe initial endpoint swap gives . The later two-element calls either see increasing keys or equal keys, so they make no swap. The two records with key 2 have reversed their original order, contradicting stable sorting. The example uses length three, where the intended current-length split is unambiguous.
Articles by others on the same topic
There are currently no matching articles.