There’s not been a lot of AppleScript posted around here lately, so I thought I’d post a heapsort, just for interest.
The heapsort algorithm was brought into the world by J.W.J. (Bill) Williams in 1964 along with the “heap” data structure it uses. It’s quite fast, although generally not as fast as quicksort or merge sort. It’s not “stable” in the sort algorithm sense. Its main claim to usefulness is that it sorts entirely in-place and is non-recursive, so it requires very little additional memory. Its two stages involve arranging the values to be sorted into a “heap” and then picking them off in reverse order and lining them up.
What Williams chose to call a “heap” is a diverging binary hierarchy. There’s a single node at the top with two child nodes beneath it. There are two child nodes beneath each child node, two child nodes beneath each of these, and so on until you run out of values. The top node contains the greatest (or co-greatest) value. Every other node contains a value that’s less than or equal to the one in the node’s parent immediately above. The order of sibling nodes’ values doesn’t matter, nor does how they compare with values anywhere on other lines of descent. But the arrangement means that the line of ascent from any node in the heap to the top consists of values that are in order. Unlike a real heap, a Williams heap won’t fall over if there aren’t enough values to complete its lowest level.
Another confusion when thinking “heap” is that the notional two-dimensional structure is folded down into the single dimension of the list being sorted! The top node comes first, followed by its two children, then the first child’s two children, then the second child’s two children, then the first child’s first child’s two children, and so on. Navigation’s easy in a binary heap that begins at list index 1: the index of any node’s first child is simply the node’s index times 2 and the other child’s index 1 more than that. But this doesn’t work if the sort range doesn’t start at 1 or if the heap structure’s anything other than binary (see below). I’ve managed to work out a formula for a constant which, when subtracted from a (node index * number of children per node) result, gives the index of the node’s first child whatever the situation. For want of a better description, I’ve labelled it const in the script below.
The mechanism for arranging the values in a heap is called “sifting down”. If the value in a parent node is less than the greater of the node’s children’s values, it’s swapped* with that greater value. The process is then repeated at the child node from which the greater value came and continues downwards until the sifted value reaches a node which has no children with values greater than the sifted one or which has no children at all. At that point the sifted value’s reached a suitable place in the heap and the values with which it’s been swapped on the way down have all moved up a level.
* “Swapped” is a convenience term here, of course. It’s more efficient just to move the other values up and then insert the sifted value into the destination slot when it’s reached.
A variant sift-down by Robert Floyd just follows the line of greater siblings down to the bottom of the heap, not comparing the sifted value with any on the way. It then retraces its steps, comparing the sifted value with the values it passed on the way down until it finds a suitable location. The current values there and above are then moved up and the sifted value inserted. The theory is that the sifted value’s most likely to end up in the lower part of the heap, especially during the second stage of the sort, so statistically there’ll be fewer comparisons if it’s compared with values below the destination instead of with those above it and the sort will be faster. Sounds good, but my implementations of it in AppleScript have all produced consistently slower sorts than with the Williams original.
The sort’s heap-building stage involves sifting down from every potential parent-node in the sort range, last to first. This can be thought of as starting with a small heap and gradually incorporating it into larger ones. The unpicking-and-ordering stage repeatedly removes the highest value left in the heap from the top to the heap’s current end position, after which that position no longer counts as part of the heap and the values from there to the end of the range are in order. The value displaced from the end position is sifted back into the reduced heap from the top, which also brings the next highest value to the top. This is repeated until the heap’s used up.
A heap doesn’t have to be binary. A ternary, quaternary, or even quinary heap can give slightly faster sorts. More comparisons will be needed at each node, but there’ll be fewer levels and so fewer nodes to negotiate on the way down. The variable c in the script below sets the number of children per node. It even works with 1 for a unary heap, although the sort will be dramatically slower because the building stage is then a mirror-image insertion sort and the ordering stage a convoluted way of reversing the result!
(* Heapsort
Heapsort algorithm: J.W.J. (Bill) Williams, 1964.
AppleScript implementation: Nigel Garvey, 2008/2024/2026.
*)
(* Sort theList's items l thru r. *)
on heapSort(theList, l, r)
(* Process the handler parameters. *)
set listLen to (count theList)
if (listLen < 2) then return
-- Negative and/or transposed range indices.
if (l < 0) then set l to listLen + l + 1
if (r < 0) then set r to listLen + r + 1
if (l > r) then set {l, r} to {r, l}
set c to 5 -- Number of children per heap node. Adjust to taste. A quinary heap's good.
script o
property cMinus1 : c - 1 -- Nominal difference between a node's first and last child indices.
property const : l * cMinus1 - 1 -- Constant for use in index-of-first-child calculations.
property lst : theList
on siftDown(siftVal, n, endOfHeap) -- (value to sift down, entry node index, heap end index)
set childX to n * c - const -- Index of n's child node of interest, initially the first.
repeat until (childX comes after endOfHeap) -- End the sift-down here if n's childless.
-- Which of n's child nodes contains the greatest value and what is it?
set hiVal to my lst's item childX
set lastChild to childX + cMinus1
if (lastChild comes after endOfHeap) then set lastChild to endOfHeap
repeat with nextChild from (childX + 1) to lastChild
set nextVal to my lst's item nextChild
if (nextVal > hiVal) then
set childX to nextChild
set hiVal to nextVal
end if
end repeat
-- If the greatest child node value's > siftVal, move it up to n and prepare to continue sifting-down
-- from the vacated child node. Otherwise none of the values is greater than siftVal, so end the sift-down here.
if (hiVal > siftVal) then
set my lst's item n to hiVal
set n to childX
set childX to n * c - const
else
exit repeat
end if
end repeat
-- Insert the sifted value at the n reached.
set my lst's item n to siftVal
end siftDown
end script
(* Do the sort. *)
-- Build and arrange the heap, starting with a small one and gradually growing larger ones over it.
repeat with topOfHeap from (l + (r - l - 1) div c) to l by -1
o's siftDown(o's lst's item topOfHeap, topOfHeap, r)
end repeat
-- Order the sort range from the end by repeatedly removing the highest value left in the heap from the top to the heap's
-- current end and sifting the displaced end value back into the reduced heap from the top, until the heap's used up.
repeat with endOfHeap from r to (topOfHeap + 1) by -1
set endVal to o's lst's item endOfHeap
set o's lst's item endOfHeap to o's lst's item topOfHeap
o's siftDown(endVal, topOfHeap, endOfHeap - 1)
end repeat
return -- nothing
end heapSort
--(*
on demo()
script o
property lst : {}
end script
repeat 1000 times
set o's lst's end to (random number 10000)
end repeat
-- Sort o's lst's items 1 thru -1
heapSort(o's lst, 1, -1)
return o's lst
end demo
demo()
--*)