Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions src/helper/MinHeap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace Src\helper;

class MinHeap
{
private array $heap;

/**
* @param array<int, int|float> $data to be inserted into the heap
*/
public function __construct(array $data) {
foreach ($data as $item) {
$this->insert($item);
}
}

/**
* Insert the provided into the heap
*
* @param int|float $value
* @return void
*/
public function insert(int|float $value): void
{
$length = count($this->heap);
$this->heap[$length] = $value;
if ($length == 0) {
return;
}
$index = $length;
while ($index > 0 && $this->heap[(int)(($index - 1) / 2)] < $value) {
[$this->heap[(int)(($index - 1) / 2)], $this->heap[$index]] = [$this->heap[$index], $this->heap[(int)(($index - 1) / 2)]];
$index = (int)(($index - 1) / 2);
}
}

/**
* Delete the provided value from the heap
*
* @param int|float $value
* @return void
*/
public function delete(int|float $value): void {}

/**
* Returns the min value of the heap or null if heap is empty.
*
* @return int|float|null The peak value, or null if not applicable.
*/
public function peak(): int|float|null
{
return $this->heap[0] ?? null;
}

/**
* Heapify the array
*
* @return void
*/
private function heapify(): void {}
}
Loading