首页 > 编程语言 > 详细

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

时间:2016-07-08 09:00:19      阅读:251      评论:0      收藏:0      [点我收藏+]

#1,简介

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

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

 

#2,c++实现

#include<iostream>
#include<vector>

using namespace std;

void BubbleSort(vector<int> &a);
void swapv(int &a, int &b);

int main(){
  vector<int> array = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 };

  BubbleSort(array);

  cout<<"The sorted array is: "<<endl;
  for (vector<int>::iterator iter = array.begin(); iter != array.end(); iter++)
  cout<< *iter <<"\t";
  cout<<endl;

  system("Pause");
  return 0;
}

void BubbleSort(vector<int> &a){
  int len=a.size();
  int index = 0;

  do{
    index=0;
    for (int i = 0; i<len - 1; i++){
      if(a[i]>a[i+1]){
        swapv(a[i],a[i+1]);
        index++;
      }
    }
  } while (index != 0);
}

void swapv(int &a, int &b){
  a=a+b;
  b=a-b;
  a=a-b;
}

 

#3,程序运行结果

技术分享

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

原文:http://www.cnblogs.com/sophia-hxw/p/5652148.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!