我试图理解此代码,但我不理解该do..while
循环while(swapped)
。停止while循环的条件是什么?
/* 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);
}
在迭代中没有交换任何元素时,循环将停止。正如您在循环开始时所看到的那样,将其swapped
设置为0。当无法交换元素时,程序将进入if (ptr1->data > ptr1->next->data)
条件,并且在这种情况下swapped
将其设置为1(C的C版本true
)。循环将一直持续到swapped
1。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句