冒泡排序基本思想
在第0次循环中:从第0个元素开始,将两个相邻的元素两两比较,如果逆序则交换顺序。这样比较次(只有
个数对)以后,最后的元素就是最大的元素。(之所以称之为冒泡排序,是因为关键字大的元素就像冒泡一样依次地浮出水面)
这样依次进行次循环,这样序列就有序了。
以比较次数作为基本操作分析:
平均时间复杂度:
最好时间复杂度:
最坏时间复杂度:
特性
1.具有稳定性。
2.冒泡排序是快速排序的基础。
//冒泡排序
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
void swap(int& a,int &b){//交换元素,注意是引用
int temp = a;
a = b;
b = temp;
}
void bubbleSort(int a[],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j+1]<a[j]) swap(a[j+1],a[j]);//如果出现逆序就交换
}
}
}
int main(void)
{
int n = 10;
int arr[10] = {0};
for(int i=0;i<n;i++)
{
arr[i]=rand()%1000;
}
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
bubbleSort(arr,10);
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}