提交 f70cab20 编写于 作者: 独孤过's avatar 独孤过

优化冒泡排序

上级 c1000709
#include <stdbool.h>
#include "gtsort.h"
void sort(
......@@ -12,10 +14,21 @@ void sort(
void *context = NULL;
void *left, *right;
for (size_t i = num - 1, j; i > 0; --i)
bool swapped = true; // 内层循环交换元素的标记
/*
* 如果内层循环未交换元素,表明元素已经有序,
* 结束外层循环,减少循环和比较次数
*/
for (size_t i = num - 1, j; swapped && i > 0; --i)
{
swapped = false;
for (j = 0; j < i; ++j)
if (comp(left = address(ptr, j, size), \
right = address(ptr, j + 1, size), ctx) > 0)
{
context = swap(left, right, size, context);
swapped = true;
}
}
swap(NULL, NULL, 0, context);
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册