Search code examples
carrayssortingstructureshallow-copy

Sorting of an array


I am programming in C. I have an array of structures. I need to print the array in sorted order based on an element of the structure. The main problem where I am stuck is I do not want to modify the original array.

For example: My array is proctab[10]. This is the array of structure named pentry.

struct pentry
{
    int a;
    int b;
    char c;
}

I need to print as follows:

a = 1, b = 2, c = a
a = 2, b = 1, c = d
a = 3, b = 0, c = e
a = 4, b = 1, c = a
a = 4, b = 2, c = a

and so on.. i.e. the result is sorted on a. but if a has same value for two structures in the array, the array should be sorted on b as well.

I want the original array proctab to remain intact.

Is there any way to do this?


Solution

  • To sort the items without messing with the original array, create a second array of references:

    struct pentry plist[]= { { 1, 2, 'a' }, { 4, 8, 'z' }, { 2, 7, 'c' }, { 2, 1, 'e' }, { 5, 6, 'b' } ;
    struct pentry (* pref)[5] ;
    
    int compare( const struct pentry ** px, const struct pentry ** py )
    {
      return ( (** px).a == (** py).a ) ? ( (** py).b - (** px).a ) : ( (** py).a - (** px).a ) ;
    }
    
    void dosort( struct pentry ** zdest, struct pentry * asrc, int n )
    {
      int i ;
      struct pentry ** fill ;
    
      for ( i= n, fill= zdest ; ( i -- ) ; ) { *( fill ++)= asrc ++ ; }
      qsort( zdest, n, sizeof( * zdest ), compare ) ;
    }
    
    void show_sorted( struct pentry ** aref, int n )
    {
      while ( n -- )
      {
        printf("%d %d %c\n", (** aref).a, (** aref).b, (** aref).c ) ;
        ++ aref ;
      }
    }
    
    int main()
    {
      dosort( pref, plist, sizeof( plist) / sizeof( * plist)) ;
      show_sorted( pref, sizeof( plist) / sizeof( * plist)) ;
      return 0 ;
    }