insertion sort and string sorting

M

Mariano

I have a structure with a numeric field and a pointer to char:

typedef struct s
{
int numero;
char *carattere;
} strutt;

I have created, then, an array of structure:

strutt *arr;
arr = (strutt *)malloc(32 * sizeof(strutt));

I can insert a new element as:
arr[0].numero = 5;
arr[0].carattere = "qwerty"

When this dynamic array of structure will be full, it can be necessary
to sort it. I need to sort it with insertion sort algorithm, this is
how I have implemented:

void insertion_sort(strutt *x, int length)
{
strutt key;
int i,j=1,scambi=0;
for(j=1;j<length;j++)
{
key = x[j];
i=j-1;
while(x.numero>key.numero && i>=0)
{
x[i+1] = x;
i--;
}
x[i+1] = key;
}
}

This function works perfectly if I need to sort integer number (order
by field "numero"). But what if I need to modify this algorithm to
make it working with "Carattere" field???
 
E

Eric Sosman

Mariano said:
I have a structure with a numeric field and a pointer to char:

typedef struct s
{
int numero;
char *carattere;
} strutt;

I have created, then, an array of structure:

strutt *arr;
arr = (strutt *)malloc(32 * sizeof(strutt));

I can insert a new element as:
arr[0].numero = 5;
arr[0].carattere = "qwerty"

When this dynamic array of structure will be full, it can be necessary
to sort it. I need to sort it with insertion sort algorithm, this is
how I have implemented:

void insertion_sort(strutt *x, int length)
{
strutt key;
int i,j=1,scambi=0;
for(j=1;j<length;j++)
{
key = x[j];
i=j-1;
while(x.numero>key.numero && i>=0)
{
x[i+1] = x;
i--;
}
x[i+1] = key;
}
}

This function works perfectly if I need to sort integer number (order
by field "numero"). But what if I need to modify this algorithm to
make it working with "Carattere" field???


Then you compare those fields instead of the numero fields.
How do you compare strings? With strcmp(), usually. So instead
of using

while (x.numero > key.numero ...

you would use

while (strcmp(x.carattere, key.carattere) > 0 ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top