求职基础复习之冒泡排序c++版
代码中在第一层循环中增加一个bool值,是为了防止在排序完成后还继续无谓的比较,最多会有(n-1)*(n-2)/2次循环。
1 #include<iostream> 2 using namespace std; 3 void bumbleSort(int a[],int l) 4 { 5 for(int i = 0;i<l;i++) 6 { 7 bool b = true; 8 9 for(int j = 0;j<l-i-1;j++) 10 { 11 12 if(a[j]>a[j+1]) 13 { 14 if(b) 15 b = false; 16 int temp = a[j]; 17 a[j] = a[j+1]; 18 a[j+1] = temp; 19 } 20 21 } 22 if(b) 23 break; 24 } 25 } 26 int main() 27 { 28 int a[6] = {9,-9,3,-3,0,0}; 29 for(int i = 0;i<6;i++) 30 cout<<a[i]<<" "; 31 32 bumbleSort(a,6); 33 for(int i = 0;i<6;i++) 34 cout<<a[i]<<" "; 35 cout<<endl; 36 }