Using C programming
I have a file that contains earthquake data that I will copy and paste below. I want to use either bubble or insertion sort to sort the file by latitude in ascending order, then create a new file containing the sorted data. I also want to do this program using multiple threads concurrently in order to speed up the sorting process.
example file to sort:
time,latitude,longitude,depth,mag,magType,nst,gap,dmin,rms,net
2020-10-17T17:22:03.840Z,32.877,-116.2991667,0.31,1.16,ml,21,119,0.07747,0.26,ci
2020-10-17T17:17:29.980Z,34.1611667,-116.452,2.75,0.87,ml,17,66,0.05224,0.22,ci
2020-10-17T17:03:54.460Z,33.5396667,-116.4613333,8.66,0.63,ml,18,126,0.06084,0.16,ci
2020-10-17T16:55:01.080Z,63.254,-151.5232,8,1.4,ml,,,,0.9,ak
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
// Structure to store various contents of the file
struct earthquake
{
    char beg[100];      // To store the content of file before latitude
    float latitude;     // To store the latitude
    char end[200];      // To store the contents of the file after the latitude part
} quakes[100];
int main()
{
    // Opening files
    FILE *infile = fopen("earthquake.txt", "r");
    FILE *outfile = fopen("sorted_quake.txt", "w");
    // Creating a temporary struct of the type earthquake
    struct earthquake temp;
    char ch;
    int i=0;
    char header[100];
    // Reading the header i.e. column names from the file
    fscanf(infile, "%s", header);
    // Writing the header to the output file
    fprintf(outfile, "%s\n", header);
    ch = fgetc(infile);
    char line[200];
    // Loop to run till end of file is reached
    while(ch != EOF)
    {
        // Reading a line of the file
        fscanf(infile, "%s", line);
       Â
        // Splitting the line into three parts by first and second comma
        // and storing the parts into respective elements of the structure
        strcpy(quakes[i].beg, strtok(line, ","));
        quakes[i].latitude =  atof(strtok(NULL,","));
        strcpy(quakes[i].end, strtok(NULL, ""));
        ch = fgetc(infile);
        i++;
    }
    int size = i;
    // Bubble sort implementation to sort the earthquakes data in ascending order based on latitude.
    for(i=1; i<size; i++)
        for(int j=0; j<size-i; j++)
            if (quakes[j+1].latitude < quakes[j].latitude)
            {
                temp = quakes[j];
                quakes[j] = quakes[j+1];
                quakes[j+1] = temp;
            }
   Â
    // Writing the sorted data of earthquakes to the output file.
    for(i=0; i<size; i++)
        fprintf(outfile, "%s,%f,%s\n", quakes[i].beg, quakes[i].latitude, quakes[i].end);
   Â
    return 0;
}
Please upvote if you found this answer useful or drop-in the comment's section your queries. I will try to assist you with the best possible solution.
Get Answers For Free
Most questions answered within 1 hours.