0

Please send a sollution to this . I have a csv file named file.csv. I need to read that using array and then sort them based on the column. please can you help in the sorting technique.

3
Contributors
5
Replies
7
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

here is my code

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
   struct{
             char name[10];
             char code[10];
             char designation[10];
             char gender[10];
            } employee_details[15];

       FILE *fp;
       char buf[50];
       int i=0,j;
       fp=fopen("file.csv","r");
       while(fgets(buf,sizeof(buf),fp)!=NULL)
        {
             strcpy(employee_details[i].name,strtok(buf,","));
             strcpy(employee_details[i].code,strtok(buf,","));
             strcpy(employee_details[i].designation,strtok(buf,","));
             strcpy(employee_details[i].gender,strtok(buf,","));
             ++i;
        }
        for(j=0;j<10;j++)
         {
            printf("employee:%s","employee_details[j]);

          }
        fclose (fp);
}

I am new to the concept of C programming. So please can you guide me regarding the sorting for each of the column .

0

do you know how to code bubble sort? or any other sorting algorithm ? If yes, then sorting structures is nearly the same thing except instead of swapping integers you swap whole structures. But it runs a lot faster if you use an array of pointers to structures instead of an array of structures because all you have to swap are the pointers.

0

Hi thank you for providing the sollution. I know bubble sort and i have applied the method too. but dont know in terms of array of pointers. i know only this way,since I dont have much knowledge of pointers.

void sort(int arr[],int size)
{
  int temp,i,j;
   for (i=0;i<size;i++)
   {   
     for(j=0;j<size-i-1;j++)
    {  
        if (arr[j]<arr[j+1])
        {
            temp=arr[j];
            arr[j]=arr[j+1];
            arr[j+1]=temp;
         }
     }
  }
}
0

pretty simple -- just replace the array of ints with an array of structures and make temp a structure data type instead of int.

Not sure where you got that algorith, but its a little off -- the inner loop should run from i+1 to size. I think the below will run slightly faster because fewer iterations.

void sort(int arr[],int size)
{
  int temp,i,j;
   for (i=0;i<size-1;i++)
   {   
     for(j=i+1;j<size;j++)
    {  
        if (arr[i]<arr[j])
        {
            temp=arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
         }
     }
  }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.