1

I need to know how to use qsort to sort structures on the basis of just one field in the structure.

for eg.

struct abc {
    double* field;
    int* class;    
}

Each field has a corresponding class i.e class associated to field[i] is class[i]. I need to sort the double* field in ascending order and at the same time assign the original class values to each field.

PeteBeat
  • 271
  • 4
  • 11
  • Classes in C? Instead of comparing objects (structs), compare it's elemets - in this case - fields. – Kamiccolo Apr 16 '14 at 16:59
  • @Pranav do you mean sorting a list of abc structs? – rw.liang1 Apr 16 '14 at 18:24
  • How do you determine the number of elements in `field` and in `class`? – chux - Reinstate Monica Apr 16 '14 at 18:52
  • @Kamiccolo There are no classes. The name of my int* is a class. liangricha Yes I want to sort the column in the ascending order of field. But since each field has a corresponding value of class, I need to sort that value as well. – PeteBeat Apr 16 '14 at 21:23
  • This is isomorphic with the duplicate — the duplicate needs to sort 4 parallel arrays whereas this sorts just 2 (but the 4 arrays are all the same type, not 2 different types as here). However, the principles are the same. You cannot use standard C `qsort()` unless you transform the data from a structure holding arrays to an array of structures, and use O(N) preprocessing to convert to array of structures and O(N) postprocessing to convert back to the structure holding arrays. It also requires twice as much storage. The alternative is custom sort code that manages swapping multiple arrays. – Jonathan Leffler Sep 02 '19 at 03:00

0 Answers0