现在的位置: 首页 > 综合 > 正文

冒泡排序(正宗点吧)

2017年11月15日 ⁄ 综合 ⁄ 共 561字 ⁄ 字号 评论关闭
#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();
	int flag;
	for(auto i =0;i < n;i++)
	{
		flag =false;
		for(auto j=n-1;j >i;j--)
		{
			if(v[j-1] > v[j])
			{
				swap(v[j-1],v[j]);
				flag =true;
			}
		}
		if(!flag) return v;
	}
	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");
}

 

抱歉!评论已关闭.