The data structure you are looking for is a binary tree, where the left child is smaller than the parent and the right child is greater than the parent. Then a simple in-order traversal would give you the sorted list at the end in O(n)
time, which is optimal. (Or O(1)
per element.)
You do NOT want a min-heap because every time the minimum is retrieved from the heap, you need to spend O(log(n))
time before you can retrieve the next minimum item, which results in the total time of O(nlog(n))
, which you are trying to avoid.
The difficulty in using binary trees come from having to ensure that the tree remains balanced. Otherwise the worst case time complexity is O(n)
for each insertion. O(log(n))
worse case time algorithm is known for keeping the tree balanced after each insertion, but is not the simplest algorithm to implement. I've done a quick Google search and there seems to be already existing Binary Tree implementations in PHP.
This is the general idea behind what is known as Tree sort.