zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ 冒泡排序与sort函数

C++ 函数 Sort 冒泡排序
2023-09-27 14:25:48 时间

步骤和原理,上两张图:

代码实现:

#include<iostream>
using namespace std;

int main()
{
	int arr[] = { 1, 3, 5, 7, 9, 2, 4, 8, 6, 10 };
	int arrLength = sizeof(arr) / sizeof(arr[0]);
	cout << "排序前:";
	for (int i = 0; i < arrLength; i++)
		cout << arr[i]<<" ";
	for (int i = 0; i < arrLength-1; i++) //排序总轮数 = 元素个数 - 1
	{
		for (int j = 0; j < arrLength - i - 1; j++) //每轮对比次数 = 元素个数 - 排序总轮数 - 1
		{
			if(arr[j] > arr[j + 1])
			{
				int temp = arr[j + 1];
				arr[j + 1] = arr[j];
				arr[j] = temp;
			}
		}
	}
	cout << "\n排序后:";
	for (int i = 0; i < arrLength; i++)
		cout << arr[i] << " ";
	cout << endl;
	return 0;
}

运行结果: 

 

当然C++ sort函数可以快速实现从小到大或从大到小排列数组:

#include<iostream>
#include<algorithm>
using namespace std;

bool compare(int a, int b);

int main()
{
	int arr[] = { 1, 3, 5, 7, 9, 2, 4, 8, 6, 10 };
	int arrLength = sizeof(arr) / sizeof(arr[0]);
	cout << "排序前:";
	for (int i = 0; i < arrLength; i++)
		cout << arr[i] << " ";
	//sort(arr, arr + arrLength); //默认从小到大顺序排列
	sort(arr, arr + arrLength, compare); //指定从大到小顺序排列
	cout << "\n排序后:";
	for (int i = 0; i < arrLength; i++)
		cout << arr[i] << " ";
	cout << endl;
}

//自定义函数
bool compare(int a, int b)
{
	return a > b;
}