冒泡排序是一种简单的排序算法,它的思想是重复地遍历待排序的序列,比较相邻的两个元素,如果它们的顺序不正确,就交换它们的位置。这样,每一次遍历都会将序列中最大的元素"冒泡"到序列的末尾。重复这个过程,直到整个序列都有序。
下面是一个用 C++ 实现的冒泡排序的例子:
#include <iostream>
#include <vector>
using namespace std;
void bubbleSort(vector<int>& array)
{
const auto n = array.size();
if (n <= 1)
{
return;
}
for (unsigned int i = 0; i < n - 1; ++i)
{
// Bubble out the max value
for (unsigned int j = 0; j < n - 1 - i; ++j)
{
if (array[j] > array[j + 1])
{
const int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
int main(int argc, char* argv[])
{
// Create an array to test sort method
vector<int> array = {
2, 3, 4, 0, 7};
cout << "Before sorting: ";
for (int i = 0; i < array.size(); ++i)
{
cout << array[i] << " ";
}
cout << endl;
bubbleSort(array);
cout << "After sorting: ";
for (int i = 0; i < array.size(); ++i)
{
cout << array[i] << " ";
}
cout << endl;
return 0;
}
在这个例子中,我们定义了一个名为 bubbleSort 的函数来实现冒泡排序。在函数中,我们使用两个嵌套的循环来遍历数组。外层循环控制需要遍历的次数,内层循环比较相邻的元素并进行交换。最后,我们在主函数中调用 bubbleSort 函数对数组进行排序,并输出排序后的结果。
对于冒泡排序,它需要进行 n − 1 n-1 n−1 轮排序,每轮排序需要比较 n − i n-i n−i 次,因此总的比较次数是一个等差数列
( n − 1 ) + ( n − 2 ) + . . . + 2 + 1 = n + n ( n − 1 ) 2 (n-1) + (n-2) + ... + 2 + 1 = n + \frac{n(n-1)}{2} (n−1)+(n−2)+...+2+1=n+2n(n−1)
即 O ( n 2 ) O(n^2) O(n2)。另外,由于冒泡排序是原地排序算法,因此它的空间复杂度为 O ( 1 ) O(1) O(1)。