### Braun trees: size computed in time O(log^2(n))

```algorithm from a paper by Okasaki
Three Algorithms on Braun Trees (Functional Pearl)
JFP 7 (6), 1997```
parent 2289299d
 (** Purely applicative heaps implemented with Braun trees. Braun trees are binary trees where, for each node, the left subtree has the same size of the right subtree or is one element larger (predicate [inv]). Consequently, a Braun tree has logarithmic height (lemma [inv_height]). The nice thing with Braun trees is that we do not need extra information to ensure logarithmic height. We also prove an algorithm from Okasaki to compute the size of a braun tree in time O(log^2(n)) (function [fast_size]). Author: Jean-Christophe Filliâtre (CNRS) *) ... ... @@ -184,6 +195,44 @@ module BraunHeaps | Node l _ r -> merge l r end (** The size of a Braun tree can be computed in time O(log^2(n)) from Three Algorithms on Braun Trees (Functional Pearl) Chris Okasaki J. Functional Programming 7 (6) 661–666, November 1997 *) use import int.ComputerDivision let rec diff (m: int) (t: tree elt) requires { inv t } requires { 0 <= m <= size t <= m + 1 } variant { t } ensures { size t = m + result } = match t with | Empty -> 0 | Node l _ r -> if m = 0 then 1 else if mod m 2 = 1 then (* m = 2k + 1 *) diff (div m 2) l else (* m = 2k + 2 *) diff (div (m - 1) 2) r end let rec fast_size (t: tree elt) : int requires { inv t} variant { t } ensures { result = size t } = match t with | Empty -> 0 | Node l _ r -> let m = size r in 1 + 2 * m + diff m l end (** A Braun tree has a logarithmic height *) use import bintree.Height ... ...
 ... ... @@ -4,8 +4,8 @@ ... ... @@ -286,53 +286,103 @@ ... ...
No preview for this file type
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!