So having not waited for an answer in this topic, I decided to implement my data structure.
The problem I encountered: when sorting small lists, everything is fine, but when sorting a list with a size of 487 items, a stack overflow occurs in the merge
method.
Here are the parts of the code responsible for sorting.
Any ideas?
private function mergeSort($node) {
if ($node == null || $node->next == null) {
return $node;
}
$second = $this->split($node);
$node = $this->mergeSort($node);
$second = $this->mergeSort($second);
return $this->merge($node, $second);
}
private function split(Word $word) {
$fast = $word;
$slow = $word;
while ($fast->next !== null && $fast->next->next !== null) {
$fast = $fast->next->next;
$slow = $slow->next;
}
$temp = $slow->next;
$slow->next = null;
return $temp;
}
private function merge($first, $second) {
if ($first === null) {
return $second;
}
if ($second === null) {
return $first;
}
if ($first->begin < $second->begin) {
$first->next = $this->merge($first->next, $second);
$first->next->prev = $first;
$first->prev = null;
return $first;
} else {
$second->next = $this->merge($first, $second->next);
$second->next->prev = $second;
$second->prev = null;
return $second;
}
}
Usage:
//some code here
$sortedLinedList = $linkedList->mergeSort($linkedList->head);
// stack overflow happens
Update:
I found out that the stack overflow does not always directly depend on the number of items in the list. Sometimes the stack can overflow with 350 elements, and sometimes with 487. Perhaps it depends on the data of the list itself. The only place where I use the node data directly is the comparison in the merge
method. Maybe it happens because the variable "begin" contains the value of float type? I tried this:
round($first->begin, 2) < round($second->begin, 2)
but It didn't help me :(