I’m not very advanced in the sorting part of programming yet, so I was looking for some help with my algorithm.
void sortList()
{
Item_PTR tmpNxt = current->nextItem;
Item_PTR tmpPTR = current;
int a, tmp;
while(tmpNxt != NULL)
{
a = tmpPTR->value;
while(tmpNxt != tmpPTR && tmpNxt->value < a)
{
tmp = a;
tmpPTR->value = tmpNxt->value;
tmpNxt->value = tmp;
tmpPTR = tmpPTR->nextItem;
}
tmpPTR = current;
tmpNxt = tmpNxt->nextItem;
}
}
The list state before sorting: 9 8 7 6 5 4 3 2 1
after sorting: 1 9 8 7 6 5 4 3 2
I’m not sure why…I’ve played computer a lot on paper and I feel like it should work…but maybe other eyes will spot the problem.
Current is a global pointer that will always have the location of the first/ top element in the list.
This is because the function
sortList()is not changingcurrent, the “global”variable denoting the list head.
Please don’t use a global variable, and certainly not for a linked list head. (What will you do when you need two lists?)
I would redesign the
sortList()function to either one of the following:Also, make yourself familiar (even if you can’t use them in the immediate project) to the interface of C++ Standard Library for lists,
std::listlink