* Remove the greatest value from the binary heap and return it, or return * undefined if the heap is empty. * * @example Removing the greatest value from the binary heap * ```ts * import { BinaryHeap } from "@std/data-structures"; * import { assertEquals } from "@std/assert"; *
()
| 296 | * @returns The greatest value from the binary heap, or undefined if the heap is empty. |
| 297 | */ |
| 298 | pop(): T | undefined { |
| 299 | const size: number = this.#data.length - 1; |
| 300 | swap(this.#data, 0, size); |
| 301 | let parent = 0; |
| 302 | let right: number = 2 * (parent + 1); |
| 303 | let left: number = right - 1; |
| 304 | while (left < size) { |
| 305 | const greatestChild = right === size || |
| 306 | this.#compare(this.#data[left]!, this.#data[right]!) <= 0 |
| 307 | ? left |
| 308 | : right; |
| 309 | if (this.#compare(this.#data[greatestChild]!, this.#data[parent]!) < 0) { |
| 310 | swap(this.#data, parent, greatestChild); |
| 311 | parent = greatestChild; |
| 312 | } else { |
| 313 | break; |
| 314 | } |
| 315 | right = 2 * (parent + 1); |
| 316 | left = right - 1; |
| 317 | } |
| 318 | return this.#data.pop(); |
| 319 | } |
| 320 | |
| 321 | /** |
| 322 | * Add one or more values to the binary heap, returning the new length of the |
no test coverage detected