选择排序、插入排序与冒泡排序

选择排序: 

#include<iostream>
using namespace std;
int main()
{
	constexpr int SIZE = 10;
	int a[SIZE] = { 1,4,3,2,6,7,5,9,10,8 };
	//选择排序
	for (int i = 0; i != SIZE - 1; ++i)
	{
		for (int j = i + 1; j != SIZE; ++j)
		{
			if (a[j] < a[i])
			{
				int temp = a[j];
				a[j] = a[i];
				a[i] = temp;
			}
		}
	}
	for (auto r : a)
		cout << r << ends;
	cout << endl;   

	system("pause");
}

插入排序

//插入排序
	for (int i = 1; i != SIZE; ++i)
	{
		for (int j = 0; j != i; ++j)
		{
			if (a[j] > a[i])
			{
				int tmp = a[i];  //注意要将a[i]暂存,因为下面的循环会把a[i-1]赋给a[i]
				for (int k = i; k != j; --k)
					a[k] = a[k - 1];
				a[j] = tmp;
				break;
			}
		}
	}
	for (auto r : a)
		cout << r << ends;
	cout << endl;            

冒泡排序

//冒泡排序
	for (int i = SIZE - 1; i != 0; --i)
	{
		for (int j = 0; j != i; ++j)
		{
			if (a[j] > a[j + 1])
			{
				int tmp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = tmp;
			}
		}
	}
	for (auto r : a)
		cout << r << ends;
	cout << endl;

猜你喜欢

转载自blog.csdn.net/weixin_44009743/article/details/86837785