冒泡排序法实现数字从大到小排序

1、冒泡排序是非常常用的排序方法,其思想是:先选定第一个数字为最小(最大)再对数字两两进行比较,得到两者之间的最小(最大)值。具体代码实现如下:

#include 
#include 
using namespace std;

void srandData(int *, int );//产生随机数的函数
void bubbleSort(int *, int );//冒泡排序具体实现函数
void swap(int *, int *);//两个数字实现交换的函数
void display(int *, int );//在屏幕输出结果函数

int main()
{
	const int N = 10;//定义常数
	int arr[N];//定义数组
	
	srandData(arr, N);
	bubbleSort(arr, N);
	display(arr, N);

	return 0;

}

void srandData(int *a, int n)
{
	srand(time(NULL));

	for(int i = 0; i < n; i++)
	{
		a[i] = rand() % 50;//取50以下的数字
		cout << a[i] << " ";
	}

	cout << endl;
}

void swap(int *b, int *c)
{
	
	int temp = *c;
	*c = *b;
	*b = temp;
}

void bubbleSort(int *a, int n)
{

	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n - i - 1; j++)
		{
			if(a[j] < a[j + 1])
			{
				swap(&a[j], &a[j + 1]);//两者交换
			}
		}
	}
}
void display(int *d, int n)
{
	for(int i = 0; i < n; i++)
	{
		cout << d[i] << " ";
	}
	cout << endl;
}

你可能感兴趣的:(冒泡排序法实现数字从大到小排序)