c - 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);
}
解决方案
当迭代中没有交换任何元素时,循环将停止。正如您在循环开头看到的那样,它swapped
被设置为 0。当一个元素不能被交换时,程序进入if (ptr1->data > ptr1->next->data)
条件并且在这种情况下swapped
被设置为 1(这是 的 C 版本true
)。只要为swapped
1,循环就会继续。
推荐阅读
- ios - Apple Music/Music Kit:如何获取歌曲 ID?
- python - 如何捕获有关 HDFS 上文件的信息
- azure-cosmosdb - Cosmos db - 如何在一个结果的特定属性中组合不同的结果值
- go - Go 模板不渲染
- typescript - 我的集成测试和我的 ORM 之间的日期差异
- sql-server - Azure - 创建免费 SQL 数据库需要哪些角色
- c# - 如何使用 httpwebresponse 获取网站名称
- c# - 无法为路由不同于 xyz.com/api/webhooks/incoming/* 的 asp.net 通用 webhook 设置 URI
- git - 使用 git 命令获取自另一个分支的标签以来的提交次数
- javascript - javascript中符号数据类型的用例是什么?