C++ 数组排序:冒泡排序算法实现及文件保存
以下是使用冒泡排序算法实现对数组元素进行排序,并将排序结果保存到文件 out.txt 的示例代码:
#include <iostream>
#include <fstream>
using namespace std;
void SelectSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
// 交换元素
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
int main() {
int a[] = {5, 2, 8, 1, 3};
int n = sizeof(a) / sizeof(a[0]);
SelectSort(a, n);
ofstream outFile('out.txt');
if (outFile.is_open()) {
for (int i = 0; i < n; i++) {
outFile << a[i] << ' ';
}
outFile.close();
cout << '排序结果已保存到 out.txt 文件' << endl;
} else {
cout << '无法打开文件' << endl;
}
return 0;
}
这段代码首先定义了一个 SelectSort 函数,使用冒泡排序算法对数组进行排序。然后在 main 函数中定义了一个数组 a,并计算数组的长度 n。接着调用 SelectSort 函数对数组进行排序。最后打开一个名为 out.txt 的文件,并将排序结果写入文件中。如果文件打开成功,则将排序结果写入文件并关闭文件,否则输出无法打开文件的提示信息。
原文地址: https://www.cveoy.top/t/topic/fUnC 著作权归作者所有。请勿转载和采集!