Skip to content

Commit 60b7f7b

Browse files
committed
Implement quick union
1 parent d25c0f3 commit 60b7f7b

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

stdlib/lm_set.ml

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,11 +1087,31 @@ struct
10871087
| Leaf ->
10881088
s1
10891089

1090-
(* TODO: LDB: implement linear union *)
1090+
let rec merge size xs ys =
1091+
match xs, ys with
1092+
| [], _ -> size, ys
1093+
| _, [] -> size, xs
1094+
| x :: tx, y :: ty ->
1095+
if Ord.compare x y = 0
1096+
then let s, rs = merge (pred size) tx ty in
1097+
s, x :: rs
1098+
else if Ord.compare x y < 0
1099+
then let s, rs = merge size tx ys in
1100+
s, x :: rs
1101+
else let s, rs = merge size xs ty in
1102+
s, y :: rs
1103+
1104+
let compare_height x y =
1105+
compare (log2 1 (succ x)) (log2 1 (succ y))
1106+
10911107
let union s1 s2 =
10921108
let size1 = cardinality s1 in
10931109
let size2 = cardinality s2 in
1094-
if size1 < size2 then
1110+
let comp = compare_height size1 size2 in
1111+
if comp = 0 then
1112+
let s, l = (merge (size1 + size2 + 1) (to_list s1) (to_list s2)) in
1113+
treeify s l
1114+
else if comp < 0 then
10951115
union_aux s2 s1
10961116
else
10971117
union_aux s1 s2

0 commit comments

Comments
 (0)