Guest User

Untitled

a guest
Jun 20th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. exception Empty
  2.  
  3. module type ORDERED =
  4. sig
  5. type t
  6. val eq : t -> t -> bool
  7. val lt : t -> t -> bool
  8. val leq : t -> t -> bool
  9. end
  10.  
  11. module type Heap =
  12. sig
  13. type elt
  14. type t
  15.  
  16. val empty : t
  17. val is_empty : t -> bool
  18.  
  19. val insert : elt -> t -> t
  20. val merge : t * t -> t
  21.  
  22. val find_min : t -> elt
  23. val delete_min : t -> t
  24. end
  25.  
  26. module LeftistHeap(Element : ORDERED): Heap =
  27. struct
  28. type elt = Element.t
  29. type t = E | T of int * elt * t * t
  30.  
  31. let rank = function
  32. E -> 0
  33. | T (r, _, _, _) -> r
  34.  
  35. let make_t x a b =
  36. if rank a >= rank b then
  37. T (rank b + 1, x, a, b)
  38. else
  39. T (rank a + 1, x, b, a)
  40.  
  41. let empty = E
  42.  
  43. let is_empty = function
  44. E -> true
  45. | _ -> false
  46.  
  47. let rec merge = function
  48. h, E -> h
  49. | E, h -> h
  50. | T (_, x, a1, b1) as h1, (T (_, y, a2, b2) as h2) ->
  51. if (Element.leq x y) then
  52. make_t x a1 (merge(b1, h2))
  53. else
  54. make_t y a2 (merge(h1, b2))
  55.  
  56. let insert x h = merge(T (1, x, E, E), h)
  57.  
  58. let find_min = function
  59. E -> raise Empty
  60. | T (_, x, a, b) -> x
  61.  
  62. let delete_min = function
  63. E -> raise Empty
  64. | T (_, x, a, b) -> merge(a, b)
  65. end
Add Comment
Please, Sign In to add comment