基础排序算法之冒泡排序

1.主体: 两个循环;

2.时间复杂度: O(N^2);

3.过程: 对于升序,比较相邻两个数,如果第二个数小,则交换位置;

              从数列后往前比较,最终第一个数是最小的;

             重复上述步骤;

demo:

#include<iostream>
#include<vector>
using namespace std;
//冒泡排序
void my_swap(int& first, int& second)
{
	int tmp = first;
	first = second;
	second = tmp;
}
void BubbleSort(vector<int>& vec)
{
	int len = vec.size();
	for (int i = 0; i < len; i++)
	{
		for (int j = len - 1; j > i; j--)
		{
			if (vec[j] < vec[j - 1])
				my_swap(vec[j], vec[j - 1]);
		}
	}
}
int main()
{
	vector<int> arr = { 12,5,9,34,3,97,63,23,53,87,120,11,77 };
	cout << "raw val is:\n";
	for (auto i : arr)
		cout << i << "\t";
	cout << endl;

	BubbleSort(arr);
	cout << "BubbleSorted val is:\n";
	for (auto i : arr)
		cout << i << "\t";
	cout << endl;
	system("pause");
	return 0;
}

输出如下:

发布了69 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u010096608/article/details/103076111
今日推荐