My attempt of a "bubble sort" only partially works. Say for example if this is my structure declaration:
struct part {
char name [NAME_LEN+1];
char owner [OWNER_LEN+1];
char status [STATUS_LEN+1];
char date [DATE_LEN+1];
char renter [RENTER_LEN+1];
} parts [MAX_PARTS], temp [1];
and the following code print:
Piston:Mike:In::
Hook:Mark:In::
Door:Kim:In::
Axel:Matt:In::
for(i=0; i < num_parts; i++)
printf("%s:%s:%s:%s:%s\n", parts[i].name, parts[i].owner, parts[i].status, parts[i].date, parts[i].renter);
My desired final output would be sorted alphabetically by the first field like this:
Axel:Matt:In::
Door:Kim:In::
Hook:Mark:in::
Piston:Mike:In::
The following code is my attempt at sorting, but instead of my desired output I get:
::::
Axel:Matt:In::
Door:Kim:In::
Hook:Mark:In::
void status (void){
int i;
int n;
for (n=0; n < num_parts; n++){
for (i=0; i < num_parts; i++)
if (strcmp(parts[i].name, parts[i+1].name) > 0) {
temp[1]=parts[i];
parts[i]=parts[i+1];
parts[i+1]=temp[1];
}
printf("\n");
}
for(i=0; i < num_parts; i++)
printf("%s:%s:%s:%s:%s\n", parts[i].name, parts[i].owner, parts[i].status, parts[i].date, parts[i].renter);
}
From what I can see the sorting is working correctly, except that for the first time the if() statement is iterated, there is something going wrong. In this example, in the first iteration Piston (parts[0].name) and Hook (parts[1].name) are compared. They need to be switched so they are but there is a problem when the Piston line is saved to temp, I think it is being saved saved with blank fields. After this first iteration, it seems everything is working correctly, so I end up with close to what I want, but in the end parts[0] is just a bunch of blanks.
A simpler example is, if the original order is:
Hook:Matt:In::
Door:Mike:In::
the output this code gives is:
::::
Hook:Matt:In::
Can you spot my mistake?