I'm stuck. I am trying to use a selection sort to alphabetically arrange structs by strcmp the strings with each other. The problem is that I do not know how to do a selection sort with strings that are inside structs using only pointers, no indexes.
My struct looks like:
struct customer
{
char customer_name[MAX_NAME_LENGTH]; /* Last name of customer */
float amount_owed; /* Amount customer owes */
int priority; /* Priority of customer */
};
and my function call:
sort_customers(quantity, p_customer_records);
and the definition:
/**********************************************************************/
/* Sort the customer database */
/**********************************************************************/
void sort_customers(int quantity, struct customer *p_customer_start)
{
struct customer *p_customer,
*p_outer,
*p_inner,
temp_customer;
for(p_customer = p_customer_start;
(p_customer-p_customer_start) < quantity; p_customer++)
{
p_inner = p_customer;
for(p_outer = p_inner + 1;
(p_outer-p_inner) <= quantity; p_outer++)
if(strcmp(p_inner->customer_name, p_outer->customer_name) < 0)
p_inner = p_outer;
temp_customer = *p_customer;
*p_customer = *p_inner;
*p_inner = temp_customer;
p_inner++;
}
return;
}
I honestly have no clue how to do this. I haven't been able to find anything on the internet or in my books to help me with this. Right now, this function sorts the names backwards. I'm pretty sure its something easy. I'm just missing something. I think another set of eyes will help. Hopefully everything is descriptive to help anyone understand what is going on.
< 0to> 0. Or reverse the order of the arguments tostrcmp(). You should think carefully about the inner loop and its upper bound. You have elements 0..quantity-1 in the array, so I think you want a< quantitythere too; and you can marginally optimize the outer loop by looping to< quantity-1. As it stands, you're in danger of accessing the array out of bounds.