冒泡排序重复地遍历待排序的数列,每次比较两个相邻元素,如果它们的顺序错误就把它们交换。重复地进行遍历直到没有再需要交换时表示数列已经排序完成。
算法步骤:
-
比较相邻的元素:若第一个比第二个大,则交换;
-
遍历开始第一对到结尾最后一对,执行步骤1;
-
重复步骤1~2,直到排序完成。
代码展示
#include<iostream>
using namespace std;
void print(int a[],int n);
void bubbleSort(int a[], int n);
int main()
{
int a[] = {
3, 10, 0, 17, 5, 8, 2, 3, 9, 6 };
bubbleSort(a, 10);
return 0;
}
void bubbleSort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{
if (a[j + 1] < a[j])
{
int x = a[j];
a[j] = a[j + 1];
a[j + 1] = x;
}
}
cout << "第" << i << "趟冒泡后" << endl;
print(a, n);
}
}
void print(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
//cout << endl;
}
cout << endl;
cout << "-------------------------";
cout << endl;
}