一,冒泡排序法
基本思想:从第一个数开始向后比较,每次找到最大或最小的元素,把它放到开始的位置,下一次循环从刚才开始位置的下一个位置开始比较,按照这个思路从前向后进行比较。
原始版本
void bubbleSort(int *arrary, int len)
{
assert(arrary != NULL);
int i = 0;
int j = 0;
int tmp = 0;
for (i = 0; i < len;++i)
{
for (j = i+1; j < len; ++j)
{
if (arrary[i] > arrary[j])
{
tmp = arrary[i];
arrary[i] = arrary[j];
arrary[j] = tmp;
}
}
}
}
优化过后
只是对于那些本来就有序的数据就不再需要比较,直接退出。
void bubbleSort(int *arrary, int len)
{
assert(arrary != NULL);
int i = 0;
int j = 0;
int tmp = 0;
bool tag = true;
while (tag)
{
tag = false;
for (j = i+1; j < len; ++j)
{
if (arrary[i] > arrary[j])
{
tag = true;
tmp = arrary[i];
arrary[i] = arrary[j];
arrary[j] = tmp;
}
}
++i;
}
}