Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created December 2, 2019 14:49
Show Gist options
  • Save adrianosferreira/6a73c5848475d232ac3e6f83be67d07b to your computer and use it in GitHub Desktop.
Save adrianosferreira/6a73c5848475d232ac3e6f83be67d07b to your computer and use it in GitHub Desktop.
Heap in Class
<?php
class Heap {
private $items = [];
public function peek() {
if ( $this->items ) {
return $this->items[0];
}
return null;
}
public function add( $item ): void {
$this->items[] = $item;
$current = count( $this->items ) - 1;
while( $this->getParent( $current ) && $this->getParent( $current ) < $this->items[ $current ] ) {
$this->swap( $current, $this->getParentIndex( $current ) );
$current = $this->getParentIndex( $current );
}
}
public function remove(): void {
unset( $this->items[0] );
if ( ! $this->items ) {
return;
}
$lastIndex = count( $this->items );
array_unshift( $this->items, $this->items[ $lastIndex ] );
unset( $this->items[ $lastIndex ] );
$current = 0;
while ( $this->getLeft( $current ) ) {
$left = $this->getLeft( $current );
$right = $this->getRight( $current );
if ( $left > $right && $left > $this->items[ $current ] ) {
$leftIndex = $this->getLeftIndex( $current );
$this->swap( $current, $leftIndex );
$current = $leftIndex;
} elseif ( $right > $left && $right > $this->items[ $current ] ) {
$rightIndex = $this->getRightIndex( $current );
$this->swap( $current, $rightIndex );
$current = $rightIndex;
}
}
}
private function swap( $indexOne, $indexTwo ): void {
$temp = $this->items[ $indexOne ];
$this->items[ $indexOne ] = $this->items[ $indexTwo ];
$this->items[ $indexTwo ] = $temp;
}
private function getLeftIndex( $index ) {
return ( $index * 2 + 1 );
}
private function getRightIndex( $index ) {
return $index * 2 + 2;
}
private function getParentIndex( $index ) {
return (int)( ( $index - 1 ) / 2 );
}
private function getLeft( $index ) {
return isset( $this->items[ $this->getLeftIndex( $index ) ] ) ? $this->items[ $this->getLeftIndex( $index ) ] : null;
}
private function getRight( $index ) {
return isset( $this->items[ $this->getRightIndex( $index ) ] ) ? $this->items[ $this->getRightIndex( $index ) ] : null;
}
private function getParent( $index ) {
return isset( $this->items[ $this->getParentIndex( $index ) ] ) ? $this->items[ $this->getParentIndex( $index ) ] : null;
}
}
$heap = new Heap();
$heap->add( 10 );
$heap->add( 20 );
$heap->add( 30 );
$heap->add( 40 );
$heap->remove();
echo $heap->peek();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment