Re: Sorting Array of Structures



Allie wrote:
How would I go about sorting this structure by title?

Unless you have specific reason not to I would suggest looking up qsort in your C text book.

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];

Why make this an array? You only use each element once.
LIBRARY temp;

int i;

for( i = 0; i < n; i++ ) {

You are doing one too many elements. There is no element after the last element for you to compare against and possibly swap with!
for( i = 0; i < n-1; i++ ) {


if( strcmp( b[i].title, b[i + 1].title ) > 0 ) {
temp[i] = b[i];

temp = b[i];

b[i] = b[i + 1];
b[i + 1] = temp[i];

b[i+1] = temp;

}
}

return;
}

I get no errors or warnings when I compile using Bloodshed Dev-C++.

<snip>

Not surprising, your only C error is going off the end of your array, and compilers don't have to complain about that.

You also have a major algorithm error, but we only do C here not algorithms. I believe comp.programming does algorithms, so if you need to implement a sort algorithm (I'm guessing that is your assignment and your reason for not using qsort) then that is the place to ask.

However, here are some hint for you:

How can you move an element from position 2 to position 0? Your implementation can at most move it to position 1.

Google for "bubble sort" since I think that is what you are trying to implement and it is also nice and easy to understand. There are more efficient algorithms, but they are harder to understand and you should start with the simplest approach.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
.



Relevant Pages