Liking cljdoc? Tell your friends :D

Clojure Heap

A pure Clojure implementation of heap.

Installation

Available on Clojars Project

Import it using

(require '[clojure-heap.core :as heap])

Or

Copy the source code in src/clojure/clojure_heap/core.clj to your project.

Speed

Equal to the theoretical limit.

Single add: O(logn)

Single poll: O(logn)

Space: n

APIs

heap

Create a heap with a comparator[ and an entry]. O(1)

ArgumentTypeFunctionRemarks
comparatorFunctionA comparator function, deciding a max / min heapTwo arguments. Return true on matching the condition, false otherwise
[value]AnyThe first entry of the heap

Example

;; define a max heap containing maps
(def x (heap (fn [a b] (> (:id a) (:id b))) {:id 3}))
;; without initial value
(def x (heap (fn [a b] (> (:id a) (:id b)))))

get-size

Get the size (length) of heap. O(1)

ArgumentTypeFunctionRemarks
heapheap.core.HeapA heap object

Example

(def x (heap (fn [a b] (> (:id a) (:id b))) {:id 3}))
(get-size x)
;; return 1

peek

Get the top value of the heap. If it is a min heap, return the smallest value; otherwise return the largest value. Return nil if the heap is empty. O(1)

ArgumentTypeFunctionRemarks
heapheap.core.HeapA heap object

Example

(def x (heap (fn [a b] (> (:id a) (:id b))) {:id 3}))
(peek x)
;; return {:id 3}

add

Insert an entry to the heap. The heap will be reorganized to fit the new value. O(logn), n = size of the heap

ArgumentTypeFunctionRemarks
heapheap.core.HeapA heap object
valueAnyThe value to be inserted to the heapShould be applicable as one argument of the comparator

Example

(def x (heap (fn [a b] (> (:id a) (:id b))) {:id 3}))
(push x {:id 4})
(get-size x)
;; return 2

poll

Delete and return the top value of the heap. If it is a min heap, return the smallest value; otherwise return the largest value. O(logn), n = size of the heap

ArgumentTypeFunctionRemarks
heapheap.core.HeapA heap object

Example

(def x (heap (fn [a b] (> (:id a) (:id b))) {:id 3}))
(pop x)
;; return {:id 3}
(pop x)
;; return nil

Can you improve this documentation? These fine people already did:
Yuchen Liu, jiarui0000, Zhu Jiarui & clojure-finance
Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close