我需要按升序对文件中的数字列表进行排序。我已经完成了文件的所有打开并创建了我的冒泡排序功能。但我仍然坚持如何使这一切能够共同发挥作用。
my inputefile.csv
如下所示:
3,-4,-5,-8
10,30,50,-10
40,100,60,-2
void bubble_sort(char* line, int size);
int main(void)
{
FILE *file;
char* line;
int size = sizeof(line);
file = fopen("inputfile.csv", "r");
if(file == NULL)
{
printf("Unable to open the file");
}else
{
while(fgets(line, sizeof(line), file)
{
bubble_sort(line, size)
}
}
}
void bubble_sort(char* line, int size)
{
int temp, i, j;
for (i=0; i< size-1; i++)
{
for (j=0; j<size-1; j++)
{
if(line[j] > line[j+1])
{
temp = line[j];
line[j] = line[j+1];
line[j+1] = temp;
}
}
}
}
行数未知,每行有4个用逗号分隔的整数。根据我的代码,你可以说我是新手
答案 0 :(得分:-1)
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int *array, int size);
int main(void){
FILE *file;
char line[128];
if((file = fopen("inputfile.csv", "r")) == NULL){
printf("Unable to open the file");
return -1;
}
while(fgets(line, sizeof(line), file)){
int i, a[4], size = sizeof(a)/sizeof(*a);
sscanf(line, "%d,%d,%d,%d", &a[0], &a[1], &a[2], &a[3]);
bubble_sort(a, size);
for(i = 0; i < size; ++i){
printf("%d", a[i]);
if(i<size-1)
printf(", ");
}
printf("\n");
}
fclose(file);
return 0;
}
void bubble_sort(int *a, int size){
int i, temp, swap;
do{
for(swap=i=0;i<size-1;++i){
if(a[i]>a[i+1]){
swap = 1;
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
--size;
}while(swap);
}