#include<stdio.h> #include<stdlib.h> #define MaxSize 100 int main() { FILE *fp; int n=0,R[MaxSize],i; int choice1,choice2; fp=fopen("C:\\Users\\86176\\Desktop\\sort.txt","r+"); if(fp==NULL) { printf("Failed to open file."); exit(0); } printf("原始数据为:\n"); while(fscanf(fp,"%d",&R[n])==1) { printf("%d",R[n]); printf("\n"); n++; } printf("\n"); func(); printf("排序后的数据为:\n"); for(i=0;i<n;i++) { printf("%d",R[i]); printf("\n"); } fclose(fp); return 0; } 修改代码
时间: 2023-10-31 20:05:28 浏览: 90
C标准库函数集
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
FILE *fp;
int n = 0, R[MaxSize], i;
int choice1, choice2;
fp = fopen("C:\\Users\\86176\\Desktop\\sort.txt", "r+");
if (fp == NULL) {
printf("Failed to open file.");
exit(0);
}
printf("原始数据为:\n");
while (fscanf(fp, "%d", &R[n]) == 1) {
printf("%d\n", R[n]);
n++;
}
printf("\n");
bubbleSort(R, n);
printf("排序后的数据为:\n");
for (i = 0; i < n; i++) {
printf("%d\n", R[i]);
}
fclose(fp);
return 0;
}
修改后的代码实现了冒泡排序,将原始数据读入数组 R 中,对 R 进行冒泡排序,最后输出排序后的结果。
阅读全文