首页 > 解决方案 > do..while循环在链表的冒泡排序中

问题描述

我试图理解这段代码,但我不理解那个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); 
} 

标签: clinked-listbubble-sort

解决方案


当迭代中没有交换任何元素时,循环将停止。正如您在循环开头看到的那样,它swapped被设置为 0。当一个元素不能被交换时,程序进入if (ptr1->data > ptr1->next->data)条件并且在这种情况下swapped被设置为 1(这是 的 C 版本true)。只要为swapped1,循环就会继续。


推荐阅读