zoukankan      html  css  js  c++  java
  • 十大排序算法之(二)——冒泡排序

    #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 <<"	";
    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,程序运行结果

  • 相关阅读:
    ArcSDE 10.1安装、配置、连接 (SQL Server 2008)
    ASP.NET MVC 音乐商店
    ASP.NET MVC 音乐商店
    一些Web开发工具
    Apache 2 频率限制模块
    零起步高性能PHP框架 Phalcon 实战
    零配置Ubuntu下Wordpress安装
    零起步的Hadoop实践日记(hbase in action)
    零起步的Hadoop实践日记(hive in action)
    零起步的Hadoop实践日记(内存设置调整)
  • 原文地址:https://www.cnblogs.com/sophia-hxw/p/5652148.html
Copyright © 2011-2022 走看看