灵笼


私信TA

用户名:dotcpp0679722

访问量:53

签 名:

等  级
排  名 10282
经  验 1041
参赛次数 2
文章发表 2
年  龄 0
在职情况 学生
学  校 灯塔
专  业

  自我简介:

TA的其他文章

解题思路:用数组储存数据,两个for循环遍历数据,比较大小交换位置

注意事项:会用到new获取数组大小

参考代码:

#include <iostream>

using namespace std;

void swap(int *x, int *y);

int main()

{

int n;

while (cin >> n && n >= 1 && n <= 100)//省时间,结合条件n的取值范围

{

int *a = new int[n];//获取未知数组大小

for (int i = 0; i < n; i++)

cin >> a[i];

for (int j = 0; j < n; j++)

{

for (int m = 0; m < n - 1; m++)

if (a[m] > a[m + 1])

swap(&a[m], &a[m + 1]);//用两个for循环遍历,将序列靠前的较大数后移

}

for (int i = 0; i < n; i++)

{

cout << a[i] << ' ';

}

cout << endl;

}

return 0;

}


void swap(int* x, int* y)

{

int t;

t = *x;

*x = *y;

*y = t;

}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区

#include <iostream>
using namespace std;
void swap(int *x, int *y);
void sort(int* a, int* b);
int main()
{
	int n;
	while (cin >> n && n >= 1 && n <= 100)
	{
		int *a = new int[n];
		for (int i = 0; i < n; i++)
			cin >> a[i];
		int p = 0;
		while (p < n)
		{
			p++;
			for (int m = 0; m < n - 1; m++)
				sort(&a[m], &a[m + 1]);
		}
		for (int i = 0; i < n; i++)
		{
			cout << a[i] << ' ';
		}
		cout << endl;
	}
	
	return 0;
}
void sort(int* a, int* b)
{
	if (*a < *b)
		return;
	if (*a == *b)
		return;
	if(*a>*b)
		swap(*a, *b);
}
void swap(int* x, int* y)
	{int t;
	t = *x;
	*x = *y;
	*y =t}
2024-04-26 23:04:18
  • «
  • 1
  • »