When dealing with doubly-linked-lists above size 5000, I get a stack overflow error. My algorithm creates 2 new objects of the doubly-linked-list each recursion which are appended to the sorted list after each recursion. Is there an alternate way to create an object so that I don't have to do it in each recursion of the quick sort?
static void quick_sort(List sortList, Node first, Node last)
{
//Quick sort algorithm
Node left, pivNode;
List bigList = new List();
List endList = new List();
int pivot;
pivNode = first; //Sets node to become pivot (1st node in given range)
left = first.next; //Sets comparison node
pivot = first.data; //Sets integer for pivot
if (last.next != null)
{
//Creates a new list if there are nodes after last node
endList.firstNode = last.next;
last.next = null;
endList.firstNode.prev = null;
}
if (left != null)
{
do
{
if (left.data > pivot)
{
Node popNode;
popNode = left;
removeNode(popNode, sortList); //Removes node larger than pivot from sortList
left = pivNode; //Resets left node to pivNode
if (bigList.firstNode == null) //Inserts larger node into bigList
{
insertBeginning(popNode, bigList);
}
else
{
popNode.next = popNode.prev = null;
insertEnd(popNode, bigList);
}
}
if (left.data <= pivot)
{
swapNode(left, pivNode); //Swaps smaller node with pivNode(moves smaller nodes to left of list)
pivNode = left; //Resets pivNode to correct node
}
left = left.next;
} while (left != last.next); //Iterates until last given node
}
if (endList.firstNode != null)
{
//If endList exists
if (bigList.firstNode != null)
{
//If bigList exists
appendLists(bigList, endList); //Appends endList at end of bigList
}
else
{
//If bigList doesn't exist, changes it to endList
bigList = endList;
}
}
appendLists(sortList, bigList); //Appends bigList to end of sortList
if (endList.firstNode != null)
{
last = endList.firstNode.prev; //Set's correct last node
}
//Recursion until last has been fully sorted
if (pivNode.prev != first && pivNode != first)
{
quick_sort(sortList, first, pivNode.prev);
}
if (pivNode != last && first != last)
{
quick_sort(sortList, pivNode.next, last);
}
}