冒泡排序的原理:

比较两个相邻的元素,将最大的元素交换至右端(升序),每一轮都重复以上操作,最后就有顺序了。

#include <iostream>
#include <stdlib.h>
using namespace std;

/****************************************************************/
/*  冒泡排序
/***************************************************************/

void swap(int array[], int j)  // 位置互换函数
{
	int temp = array[j];
	array[j] = array[j + 1];
	array[j + 1] = temp;
}


void BubbleSort(int array[], int n)      // 冒泡排序函数
{
	for (int i = 0; i < n - 1; i++)          // n - 1 为比较的轮数。
	{
		for (int j = 0; j < n - 1 - i; j++)  // n - 1 - i 为每轮比较的次数。
		{
			if (array[j] > array[j + 1])   // 相邻的2个元素进行比较
			{
				swap(array[j], array[j + 1]);  //如果条件成立,就调用swap函数进行位置互换
			}
		}
	}
}


int main(void)  //主程序
{
	const int n = 6;  //数组元素的数量
	int array[n];
	cout << "请输入6个整数:" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> array[i];
	}

	cout << endl;  //换行

	BubbleSort(array, n);  // 调用BubbleSort函数  进行比较

	cout << "由小到大的顺序排列后:" << endl;
	for (int i = 0; i < n; i++)
	{
		cout << "array" << "[" << i << "]" << " = " << array[i] << endl;
	}

	cout << endl << endl;  //换行

	system("pause");  //调试时,黑窗口不会闪退,一直保持
	return 0;
}

运行结果:

C++ 冒泡排序算法

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2021-12-05
  • 2021-10-15
  • 2021-10-16
猜你喜欢
  • 2019-03-22
  • 2022-01-12
  • 2021-08-31
  • 2022-01-06
  • 2022-12-23
  • 2021-06-25
相关资源
相似解决方案