ThatBlueJuice
ThatBlueJuice

Reputation: 51

C programming: Sorting a integer file while keeping their original place in file

ok, here I have a small function that can sort some values written in the program

 #include <stdio.h>      /* printf */
 #include <stdlib.h>     /* qsort */
 #include <conio.h>      /* getch */

 int values[] = { 40, 10, 100, 90, 20, 25 };

 int compare (const void * a, const void * b)
 {
     return ( *(int*)a - *(int*)b );
 }

 int main ()
 {
      int n;
      qsort (values, 6, sizeof(int), compare);
      for (n=0; n<6; n++)
      printf ("%d ",values[n]);
      getch();
}

this works perfectly, there are no errors given.

Now, in my main project, I have to sort values from file. I was thinking that I could copy these values over from file and do the exact same thing as here.

However, that might seem easy, but I also need their line in file, so that means I need a second array with the numbers 1-SIZE in it. Given that my file should max out at 512 lines. what steps can I take to make this work?

Example:

User ID:              Score:
1                     13
2                     9
3                     13
4                     19
5                     8
6                     11
7                     14
8                     17

should be changed into

User ID:             Score:                  
5                    8
2                    9
6                    11
3                    13
1                    13
7                    14
8                    17
4                    19

Upvotes: 1

Views: 96

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

This is what you need

 #include <stdio.h>      /* printf */
 #include <stdlib.h>     /* qsort */

struct Element
{
    int userId;
    int score;
};

struct Element elements[] = { 
    {1, 13},
    {2,  9},
    {3, 13},
    {4, 19},
    {5,  8},
    {6, 11},
    {7, 14},
    {8, 17},
};

int ascendingSortCompareFunction (const void * a, const void * b)
{
    return (((struct Element *)a)->score - ((struct Element *)b)->score);
}

int descendingSortCompareFunction (const void * a, const void * b)
{
    return ((struct Element *)b)->score) - (((struct Element *)a)->score;
}

int main ()
{
    int n;
    int count;

    count = sizeof(elements) / sizeof(elements[0]);

    qsort(elements, count, sizeof(elements[0]), ascendingSortCompareFunction);
    printf ("UserID\tScore (Ascending Sort)\n");
    for (n = 0 ; n < count ; n++)
        printf ("%d\t%d\n", elements[n].userId, elements[n].score);

    qsort(elements, count, sizeof(elements[0]), descendingSortCompareFunction);
    printf ("UserID\tScore (Descending Sort)\n");
    for (n = 0 ; n < count ; n++)
        printf ("%d\t%d\n", elements[n].userId, elements[n].score);

    getchar();

    return 0;
}

Upvotes: 4

Related Questions