In C languange NOT C++ write a program that reads numbers from a file, sorts the
ID: 3559211 • Letter: I
Question
In C languange NOT C++ write a program that reads numbers from a file, sorts the numbers in numerical order from highest to lowest values (descending order) or vice versa (ascending order), and finally write the sorted numbers in another file. The input file will contain the number of elements in the file, type of sorting required (a or d), and the numbers.
In your program, you should follow the steps below:
i) Read the number of elements in the file
ii) Read the type of sorting (ascending or descending)
iii) Create anarray to store the numbers (size must be equal to the number read from the file)
iv) Sort the array
v) In the output file, please first write the number of elements, and the numbers in the desired order.
Explanation / Answer
// write a program that reads numbers from a file, sorts the numbers in numerical order from highest to lowest values (descending order)
// or vice versa (ascending order), and finally write the sorted numbers in another file.
// The input file will contain the number of elements in the file, type of sorting required (a or d), and the numbers.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* fin;
FILE* fout;
int *array;
int i,j,index,temp;
fin = fopen("input.txt","r");
fout = fopen("output.txt","w");
int numbers;
char option;
//In your program, you should follow the steps below:
//i) Read the number of elements in the file
fscanf(fin,"%d",&numbers);
//ii) Read the type of sorting (ascending or descending)
fscanf(fin,"%c%c",&option,&option);
//iii) Create anarray to store the numbers (size must be equal to the number read from the file)
array = (int *)(malloc(sizeof(int)*numbers));
for(i=0; i<numbers; i++)
fscanf(fin,"%d",&array[i]);
//iv) Sort the array
for(i=0; i<numbers; i++)
{
index = i;
for(j=i; j<numbers; j++)
{
if(option == 'a') { if(array[j]<array[index]) index=j;}
if(option == 'd') { if(array[j]>array[index]) index=j;}
}
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
//v) In the output file, please first write the number of elements, and the numbers in the desired order.
fprintf(fout,"%d ",numbers);
//printf("%d ",numbers);
for(i=0; i<numbers; i++)
{
fprintf(fout,"%d ",array[i]);
// printf("%d ",array[i]);
}
return 0;
}