题目:有一个文本文件origin.txt
,其中有100个整数,每个整数之间用空格隔开。 编写代码,将文件中的数据排序(升序)后写入到文件sorted.txt
中,数据之间仍然要用空格分开,
#include<stdio.h>
#include<stdlib.h>
#define MAX_NUMBERS 1024
void BubbleSort(int arr[], int length);
void WriteToFile(const char* filename, int arr[], int n);
void ReadFromFile(const char* filename, int* arr, int size);
int main() {
int numbers[MAX_NUMBERS];
ReadFromFile("origin.txt", numbers, MAX_NUMBERS);
BubbleSort(numbers, MAX_NUMBERS);
WriteToFile("sorted.txt", numbers, MAX_NUMBERS);
return 0;
}
void ReadFromFile(const char* filename, int* arr, int size) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
perror("打开文件失败");
return EXIT_FAILURE;
}
int count = 0;
int num;
while (fscanf(file, "%d", &num) == 1 && count < size) {
arr[count++] = num;
}
fclose(file);
}
void WriteToFile(const char* filename, int arr[], int n) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
perror("打开文件失败");
return EXIT_FAILURE;
}
for (int i = 0; i < n; i++) {
if (i > 0) fprintf(file, " ");
fprintf(file, "%d", arr[i]);
}
fclose(file);
}
void BubbleSort(int arr[], int length) {
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - (i + 1); j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void SelectionSort(int arr[], int length) {
int i, j, temp, min_index;
for ( i = 0; i < length - 1; i++)
{
min_index = i;
for ( j = i + 1; j < length; j++)
{
if (arr[j] < arr[j + 1]) {
min_index = j;
}
}
if (min_index != i) {
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
}