Content deleted Content added
Adding syntax highlight to a section of code, and moving the reference out of the code section to a new introductory sentence. |
|||
Line 9:
# Repeat Step 2 and 3 until the heap has only one element. Put this last element at the end of the list and output the list. The data in the list will be sorted.
Below is a C++ implementation that builds up a Max-Heap and sorts the array after the heap is built.
#include <iostream>▼
<syntaxhighlight lang="c++">
''A C++ sample heap sort code that sort an array to an increasing order''▼
using namespace std;▼
*/
{▼
void
int child = parent * 2 + 1;▼
int parent = start;
while (child <= end)▼
child ++; //take the bigger child node
if (array[parent] > array[child])
{ return; </syntaxhighlight>
== Measures of presortedness ==
Line 78 ⟶ 81:
== Algorithm ==
Adaptive heap sort is a variant of heap sort that seeks optimality (asymptotically optimal) with respect to the lower bound derived with the measure of presortedness by taking advantage of the existing order in the data. In heap sort, for a data <math>X = <x_1, x_2, x_3, .... ,x_n></math> , we put all n elements into the heap and then keep extracting the maximum (or minimum) for n times. Since the time of each max-extraction action is the logarithmic in the size of the heap, the total running time of standard heap sort is [[Big O notation|O(n log n)]].<ref name=":1" /> For adaptive heap sort, instead of putting all the elements into the heap, only the possible maximums of the data (max-candidates) will be put into the heap so that fewer runs are required when each time we try to locate the maximum(or minimum).
First, a [[Cartesian tree]] is built from the input in <math>O(n)</math> time by putting the data into a binary tree and making each node in the tree is greater(or smaller) than all its children nodes, and the root of the Cartesian tree is inserted into an empty binary heap. Then repeatedly extract the maximum from the binary heap, retrieve the maximum in the Cartesian tree, and add its left and right children (if any) which are themselves Cartesian trees, to the binary heap. If the input is already nearly sorted, the Cartesian trees will be very unbalanced, with few nodes having left and right children, resulting in the binary heap remaining small, and allowing the algorithm to sort more quickly than <math>O(n\log n)</math> for inputs that are already nearly sorted.<ref>{{Cite web|url=http://www.keithschwarz.com/interesting/code/?dir=cartesian-tree-sort|title=Archive of Interesting Code|website=www.keithschwarz.com|access-date=2019-10-31}}</ref Input: an array of n elements that need to be sorted▼
Below is an implementation in pseudo-code:<ref name=":0" />
Construct the Cartesian tree ''l''(x)▼
<syntaxhighlight>
for i = from 1 to n▼
{▼
retrieve the children in ''l''(x)▼
if the max element extracted has any children in ''l''(x)
{
insert the children element into the heap
}
}
</syntaxhighlight>
== Drawbacks ==
|