Implementing a binary heap in PHP

One of the most popular ways to implement a binary heap is using an array. Since heaps are complete binary trees, they can be easily implemented using an array. If we consider the root item to be at index 1, then the child items will be at index 2 and 3. We can represent this as i for the root and 2*i for the left child and 2*i +1 for the right child. Also, we are going to implement the mean heap as our example. So, let us get started with the class structure for the min-heap implementation.

First, we are going to start by creating a class for MinHeap, which will have two properties, one for storing the heap array and another count for the number of elements in the heap at any given moment. Here is the code ...

Get PHP 7 Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.