void sortTrain(TrainCar* head, bool ascending)
{
TrainCar* current = head;
int count = 1;
int size = (getlength(head));
if (ascending == 1)
{
for(int i = 0; i < size-1; i )
{
while(current->next)
{
if((current->load) > ((current->next)->load))
{
swapCar(head,count,count 1);
}
count ;
current = current->next;
}
}
}
if (ascending == 0)
{
for(int i = 0; i < size-1; i )
{
while(current->next)
{
if((current->load) < ((current->next)->load))
{
swapCar(head,count,count 1);
}
count ;
current = current->next;
}
}
}
}
Anyone helps me to fix the problem? I don't know how to improve it. Or any other code can do the same result? Ascending when bool ascending is true, otherwise, do descending.
CodePudding user response:
The main error in the code you posted is that you are not resetting current
and count
after each iteration of the outer loop, i.e. try the following:
// ...
if (ascending == 1)
{
for (int i = 0; i < size-1; i )
{
TrainCar* current = head;
int count = 0;
while (current->next)
{
if ((current->load) > ((current->next)->load))
{
swapCar(head, count, count 1);
}
count ;
current = current->next;
}
}
}
// ...
The above should work if swapCar
uses zero-based indices (I also changed it such that count
is initialized to zero not one : don't ever use 1-based indices in C or C ; it is just confusing to do so).
However, it is a bad design to implement swapCar
as taking indices. Each call to swapCar
is going to execute in O(n) time, if you know what that means. You already have current
and current->next
sitting there: just swap their load values, then you don't even need to maintain a count
variable at all.