1、
void bubble_sort(int *pi_array, const int i_size)
{
int i_last_swap = 0;
int i_last_swap_tmp = 0;
for (int i = 0; i < i_size; ++i)
{
i_last_swap = i_last_swap_tmp;
for (int j = i_size - 1; j > i_last_swap; --j)
{
if (pi_array[j] < pi_array[j - 1])
{
int i_tmp = pi_array[j];
pi_array[j] = pi_array[j - 1];
pi_array[j - 1] = i_tmp;
i_last_swap_tmp = j;
}
}
if (i_last_swap_tmp == i_last_swap)
{
break;
}
}
return;
}
2、优化后的冒泡排序:
template<typename T>
void BubbleSort(T *t, int n)
{
int flag = n - 1;
while (flag) {
int unordered = flag;
flag = 0;
for (int i = 0; i < unordered; ++i) {
if (t[i + 1] < t[i]) {
swap(t[i + 1], t[i]);
flag = i;
}
}
}
}