起泡排序
首先起泡排序同样分有序区和无序区。基本思想:两两比较,反序则交换位置。
由于这个特性我们就知道,一趟排序后,最后一个必然是最大的。然后第二次最后第二大又找到。
然后就很简单了直接上代码。虽然代码很简单,但是里面设计却很巧妙
#include<iostream> #include<vecotr> using namespace std; //不含暂存单元的数组v1 int temp1[]={59,20,17,36,98,14,23,83,13,28}; vector<int> v1(begin(temp1),end(temp1)); //打印数组 inline void printV(const vector<int> &v) { for(auto a:v) cout<<a<<" "; cout<<endl; } //起泡排序 void bubble_sort(vector<int> &v) { cout<<"起泡排序"<<endl; int exchange=v.size(); //定义排序区间 while(exchange!=0) //当上一趟排序有交换时候 { int bound=exchange; exchange=0; //这里设置为0假如下面for循环没有改变值说明都是正序了就退出 for(int i=0;i<bound-1;i++) //bound后面都是正序了bound-1还是乱序的 { if(v[i]>v[i+1])//假如反序则交换,且把exchange设置为i+1 { int temp=v[i]; v[i]=v[i+1]; v[i+1]=temp; exchange=i+1; cout<<"交换位"<<exchange<<endl; printV(v); } } } } int main(int argc, char *argv[]) { printV(v); bubble_sort(v); return 0; }
同样贴上打印的数据,每次交换都有