Re: Sorting Array of Structures
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Mon, 27 Feb 2006 19:38:21 GMT
Richard Heathfield <invalid@xxxxxxxxxxxxxxx> writes:
Allie said:
To Richard: qsort( book, n, sizeof( book[0] ), comptitle ); gives me
the right output. You had written qsort( book, sizeof( book ) / sizeof
(book[0] ), sizeof book[0], comptitle );
What I wrote was based on the information you gave me. If you gave me the
wrong information, that is your lookout, not mine.
Quoting the article that started this thread:
] How would I go about sorting this structure by title?
]
] typedef struct {
] char author[40];
] char title[40];
] char code[4];
] int hold;
] int loan;
] } LIBRARY;
]
] LIBRARY book[N];
]
]
] This is what I've written:
]
] void sortbytitle( LIBRARY *b, int n ) { /* n = number of books in stock
] */
] LIBRARY temp[N];
] int i;
]
] for( i = 0; i < n; i++ ) {
] if( strcmp( b[i].title, b[i + 1].title ) > 0 ) {
] temp[i] = b[i];
] b[i] = b[i + 1];
] b[i + 1] = temp[i];
] }
] }
]
] return;
] }
The code is wrong in a number of ways (the sorting algorithm doesn't
work, and the use of an array of temporaries is unnecessary), but
given the declarations of book (an array of N LIBRARY objects) and
sortbytitle (a function taking a pointer to LIBRARY and an int n,
"number of books in stock"), it seemed reasonably obvious from the
beginning that N is the total size of the array and n is the number of
array elements that contain valid values.
The use of both N and n as identifiers is legal, but confusingly poor
style.
Richard, I'm not surprised that you missed this, but it was there.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- Follow-Ups:
- Re: Sorting Array of Structures
- From: Richard Heathfield
- Re: Sorting Array of Structures
- References:
- Sorting Array of Structures
- From: Allie
- Re: Sorting Array of Structures
- From: Allie
- Re: Sorting Array of Structures
- From: Richard Heathfield
- Sorting Array of Structures
- Prev by Date: Re: Which web browser you are using
- Next by Date: Re: Whats the use of %p
- Previous by thread: Re: Sorting Array of Structures
- Next by thread: Re: Sorting Array of Structures
- Index(es):
Relevant Pages
|