冒泡排序法和选择排序法

冒泡排序法和选择排序法,第1张

冒泡排序法和选择排序法

输入一个长度为5的数组,并将其从大到小依次排序输出

#include 
using namespace std;
int main()
{
	int t;
	int i = 0, n = 4;
	int a[5];
	for (i=0; i <= 4; i++)
		cin >> a[i];
	while(n>=1)
	{
		for (i=0; i <= n - 1; i++)
			if (a[i] > a[i + 1])
				t = a[i],a[i] = a[i + 1],a[i + 1] = t;
		n--;
    }
	for (i=0; i <= 4; i++) 
		cout << a[i]< 

为何以下swap函数不能交换两变量的数值???

#include 
using namespace std;
void swap(int a, int b)
{
	int t;
	t = a;
	a = b;
	b = t;
}
int main()
{
	int t;
	int i = 0, n = 4;
	int a[5];
	for (i=0; i <= 4; i++)
		cin >> a[i];
	while(n>=1)
	{
		for (i = 0; i <= n - 1; i++)
			{
			if (a[i] < a[i + 1])
				t=a[i],a[i]=a[i+1],a[i+1]=t;
			}
		n--;
		for (i = 0; i <= 4; i++)
			cout << a[i] << " ";
		cout << endl;
    }
	for (i=0; i <= 4; i++) 
		cout << a[i]<<" ";
	int m, n1;
	cin >> m >> n1;
	swap(m, n1);
	cout << m <<" "<< n1;      //m和n1的值并未得到交换
	return 0;
}

选择排序法,输入一个数组并从小到大输出。

#include 
using namespace std;
int main()
{
	int i,j;
	int a[5];
	int t;
	for (i = 0; i<= 4; i++)cin >> a[i];
	for (i = 0; i < 5; i++)
	{
		int k = i;
		for (j = i; j < 5; j++)
			if (a[j] < a[k])k = j;
		t = a[i], a[i] = a[k], a[k] = t;
		k++;
		for (j = 0; j < 5; j++)
			cout << a[j] << " ";
		cout << endl;
	}
	cout << "最终结果" << endl;
	for (j = 0; j < 5; j++)
		cout << a[j]<< " ";
	return 0;

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3971685.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-21
下一篇 2022-10-21

发表评论

登录后才能评论

评论列表(0条)

保存