https://github.com/eneko/array-heap
A Swift Package to use arrays as heaps
https://github.com/eneko/array-heap
Last synced: 9 days ago
JSON representation
A Swift Package to use arrays as heaps
- Host: GitHub
- URL: https://github.com/eneko/array-heap
- Owner: eneko
- Created: 2023-08-13T22:52:02.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-08-13T23:14:07.000Z (almost 2 years ago)
- Last Synced: 2025-03-10T16:38:56.987Z (4 months ago)
- Language: Swift
- Size: 3.91 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# 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:
```swift
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)`:
```swift
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) |