array-heap

1.0.0

A Swift Package to use arrays as heaps
eneko/array-heap

What's New

1.0.0

2023-08-13T23:14:07Z

Initial release

array-heap

This Swift package provides an extension for using arrays of Comparable elements as heaps (both min and max).

The extension uses the array itself as the store, meaning no additional memory storage is required.

Usage

Empty arrays are already valid heaps! Because of this, elements can be inserted right away:

var heap = [Int]()
heap.minHeapInsert(2)
heap.heapTop // 2
heap.minHeapInsert(3)
heap.heapTop // 2
heap.minHeapInsert(1)
heap.heapTop // 1
heap.minHeapRemoveTop() // 1
heap.heapTop // 2

Arrays with existing items can be transformed into a heap in linear time O(n):

let items = Array(1...100)
var heap = items.maxHeapified()
heap.heapTop // 100
heap.minHeapify()
heap.heapTop // 1

Complexity

Operation Time Complexity Space Complexity
top O(1) O(1)
removeTop O(log n) O(1)
insert O(log n) O(1)
heapify/ied O(n) O(1)

Description

  • Swift Tools 5.4.0
View More Packages from this Author

Dependencies

  • None
Last updated: Tue Mar 12 2024 11:27:42 GMT-0900 (Hawaii-Aleutian Daylight Time)