54 lines
1022 B
C++
54 lines
1022 B
C++
// 接收一个数值数组,实现数组中元素值从小到大排序
|
|
// 例如:输入 3 2 1 5 4
|
|
// 输出 1 2 3 4 5
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
void show(int arr[], int size)
|
|
{
|
|
int i = 0;
|
|
while (i < size)
|
|
{
|
|
cout << arr[i] << "\t";
|
|
i++;
|
|
}
|
|
cout << endl;
|
|
}
|
|
|
|
void sort(int arr[], int size)
|
|
{
|
|
for (int i = 0; i < size - 1; i++)
|
|
{
|
|
for (int j = 0; j < size - i - 1; j++)
|
|
{
|
|
if (arr[j] > arr[j + 1])
|
|
{
|
|
arr[j] = arr[j] ^ arr[j + 1];
|
|
arr[j + 1] = arr[j] ^ arr[j + 1];
|
|
arr[j] = arr[j] ^ arr[j + 1];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
// 从键盘输入 5 个数值
|
|
int arr[5];
|
|
for (int i = 0; i < 5; i++)
|
|
{
|
|
cout << "请输入第" << i + 1 << "个数:";
|
|
cin >> arr[i];
|
|
}
|
|
cout << endl;
|
|
|
|
cout << "排序前:" << endl;
|
|
show(arr, 5);
|
|
|
|
sort(arr, 5);
|
|
cout << "排序后:" << endl;
|
|
show(arr, 5);
|
|
|
|
return 0;
|
|
} |