十大排序算法之(二)——冒泡排序

    xiaoxiao2021-04-15  25

    #1,简介

    冒泡排序是一种比较基础、简单的排序算法,它的思想就是:key值较大的会像泡泡一样被你挑选出来向后或者向前移,这具体取决于你想要的结果数组是大序排列还是小序排列。

    操作:对数组(或者其他存储结构)依次遍历,比较相邻两个元素,若与你设定的顺序相反,则交换位置,然后对数组要进行len-1次这样的遍历(len是数组长度)。

     

    #2,c++实现

    1 #include<iostream> 2 #include<vector> 3 4 using namespace std; 5 6 void BubbleSort(vector<int> &a); 7 void swapv(int &a, int &b); 8 9 int main(){ 10   vector<int> array = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 }; 11 12   BubbleSort(array); 13 14   cout<<"The sorted array is: "<<endl; 15   for (vector<int>::iterator iter = array.begin(); iter != array.end(); iter++) 16   cout<< *iter <<"\t"; 17   cout<<endl; 18 19   system("Pause"); 20   return 0; 21 } 22 23 void BubbleSort(vector<int> &a){ 24   int len=a.size(); 25   int index = 0; 26 27   do{ 28     index=0; 29     for (int i = 0; i<len - 1; i++){ 30       if(a[i]>a[i+1]){ 31         swapv(a[i],a[i+1]); 32         index++; 33       } 34     } 35   } while (index != 0); 36 } 37 38 void swapv(int &a, int &b){ 39   a=a+b; 40   b=a-b; 41   a=a-b; 42 } 冒泡排序

     

     

    #3,程序运行结果

    转载请注明原文地址: https://ju.6miu.com/read-671440.html

    最新回复(0)