Untitled

mail@pastecode.io avatar
unknown
typescript
2 months ago
562 B
4
Indexable
Never
class Heap {
    constructor(compareFunc) {
        this.compareFunc = compareFunc;
        this.heap = new Array();
    }
    
    // O(nLogN) because of sort(), but O(logN) if proper heap
    insert(val) {
        this.heap.push(val);
        this.heap.sort(this.compareFunc);
    }
    
    // O(n), but O(logN) if proper heap (due to maintaing structure of heap)
    extract() {
        return this.heap.shift();
    }
    
    // O(1)
    peek() {
        return this.heap[0];
    }
    
    // O(1)
    get size() {
        return this.heap.length;
    }
}
Leave a Comment