qfedu-basic-level/day8/homework/h4.cpp

49 lines
1006 B
C++
Raw Permalink Normal View History

2023-06-24 10:01:33 +08:00
// 输入一个整数 n然后输入 n 个整数,将它们按从大到小的顺序排序,并输出排序后的结果。
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "请输入整数 n: ";
cin >> n;
int *nums = new int[n];
int i = 0;
cout << "请输入" << n << "个整数: ";
while (i < n)
{
cin >> nums[i];
i++;
}
cout << "排序前的结果: ";
for (int i = 0; i < n; i++)
{
cout << nums[i] << "\t";
}
cout << endl;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (nums[j] < nums[j + 1])
{
nums[j] = nums[j] ^ nums[j + 1];
nums[j + 1] = nums[j] ^ nums[j + 1];
nums[j] = nums[j] ^ nums[j + 1];
}
}
}
cout << "从大到小排序后的结果: ";
for (int i = 0; i < n; i++)
{
cout << nums[i] << "\t";
}
return 0;
}