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

52 lines
1.1 KiB
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] << " ";
}
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (nums[j] > nums[j + 1])
{
/* int temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp; */
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] << " ";
}
return 0;
}