#include <iostream> #include <vector> using namespace std; void swap(int & a,int & b) { a=a+b; b=a-b; a=a-b; } vector<int> & bubbleSort(vector<int> & v) { int n=v.size(); for(auto i =0;i < n;i++) for(auto j=i;j < n;j++) { if(v[i] < v[j]) swap(v[i],v[j]); } return v; } vector<int> & bubbleSort1(vector<int> & v) { int n=v.size(); for(auto i =n-1;i >0;i--) for(auto j=0;j < i;j++) { if(v[i] < v[j]) swap(v[i],v[j]); } return v; } void print(vector<int> & v) { vector<int>::iterator pos; for(pos = v.begin();pos!=v.end();pos++) cout<<*pos<<" "; cout<<endl; } void main() { const int n=100; vector<int> v; v.reserve(n); for(int i =0;i<n;i++) v.push_back(rand()%100); print(v); //print(bubbleSort1(v)); print(bubbleSort(v)); system("pause"); }
简单选择排序
#include <iostream> #include <vector> using namespace std; void swap(int & a,int & b) { a=a+b; b=a-b; a=a-b; } void print(vector<int> & v) { vector<int>::iterator pos; for(pos = v.begin();pos!=v.end();pos++) cout<<*pos<<" "; cout<<endl; } vector<int> & simpleSelect(vector<int> & v) { int n =v.size(); int min; for(int i =0;i<n;i++) { min=i; for(int j =i+1;j<n;j++) { if(v[min]>v[j])min =j; } if(min != i)swap(v[i],v[min]); } return v; } void main() { const int n=100; vector<int> v; v.reserve(n); for(int i =0;i<n;i++) v.push_back(rand()%100); print(v); print(simpleSelect(v)); system("pause"); }