冒泡算法BubbleSort
平均时间复杂度:O(n2)
基本思想:两个数比较大小,较大的数下沉,较小的数冒起来。
过程:
比较相邻的两个数据,如果第二个数小,就交换位置。
从后向前两两比较,一直到比较最前两个数据。最终最小数被交换到起始的位置,这样第一个最小数的位置就排好了。
继续重复上述过程,依次将第2.3...n-1个最小数排好位置
c++实现代码:
void BubbleSort(int a[],int len){
int temp;//临时变量
for(int i=0;i<len;i++){
for(int j=len-1;j>i;j--){//从后向前,两两比较,小数置前
if(a[j]<a[j-1]){
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
for(int i=0;i<len;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}
int main(void){
int a[]={42,20,17,13,28,14,23,15};
cout<<"长度;"<<sizeof(a)/sizeof(int)<<endl;
BubbleSort(a,8);
system("pause");
return 0;
}
结果如下:
https://www.runoob.com/w3cnote/sort-algorithm-summary.html