冒泡排序(Bubble Sort):
重复的走访要排序的元素列,依次比较两个相邻的元素,如果顺序错误就把他们交换过来。走访元素的工作重复进行直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
这个算法的名字由来是因为越小的元素会经交换慢慢浮到数列的顶端(大的先沉底),故名冒泡排序。
时间复杂度:O(n^2);
稳定性:稳定。
C++实现:
//
// main.cpp
// bubble
#include <iostream>
using namespace std;
void bubbleSort(int *a,int n){
bool swag_flag=true;//标志位,记录每次排序是否有元素位置交换
int count=n-1;
for (int i=0; i<count&&swag_flag!=false; i++) {
swag_flag=false;//每次排序前,标志位复位
for (int j=0; j<count-i; j++) {
if (a[j]>a[j+1]) {
swag_flag=true;//发生位置交换,标志位置位
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int a[]={6,5,4,3,2,1};
int n=sizeof(a)/sizeof(int);
bubbleSort(a, n);
for (int i=0; i<n; i++) {
cout<<a[i]<<" ";
}
return 0;
}