选择排序C++的代码输出在文件里
时间: 2024-03-15 15:44:30 浏览: 15
好的,以下是选择排序的C++代码,并将排序后的结果输出到文件中:
```c++
#include <iostream>
#include <fstream>
using namespace std;
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
swap(arr[i], arr[min_idx]);
}
}
int main() {
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
ofstream output("output.txt");
if (output.is_open()) {
for (int i = 0; i < n; i++) {
output << arr[i] << " ";
}
output.close();
cout << "Sorting result is saved in output.txt" << endl;
}
else {
cout << "Unable to open file." << endl;
}
return 0;
}
```
这段代码首先定义了一个选择排序的函数`selectionSort`,然后在`main`函数中调用该函数对数组`arr`进行排序。排序后,我们打开一个输出文件流将排序结果输出到文件`output.txt`中。如果文件打开成功,则将排序结果写入文件并关闭文件流,并在控制台输出提示信息;否则,在控制台输出错误信息。