I'm trying to understand this code but i don't understand the do..while
loop with that while(swapped)
. What is the condition to stop the while loop?
/* Bubble sort the given linked list */
void bubbleSort(struct Node *start)
{
int swapped;
struct Node *ptr1;
struct Node *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
if (ptr1->data > ptr1->next->data)
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
The loop gets stopped when no element was swapped in an iteration. As you see at the beginning of the loop swapped
is set to 0. When an element cann be swapped the program enters the conndition if (ptr1->data > ptr1->next->data)
and in this condition swapped
gets set to 1 (which is the C version of true
). The loop continues as long as swapped
is 1.