sorting a character array in a structure

Hi, I was hoping to get a hint on sorting a character array, part of my homework assignment.


// This is my structure

struct item{char name[20]; int mark1; int mark2; double average;};
item person[6];

//this is how I am attempting to sort it

void alphabetical(int entries, item person[], int size)
{

item temp[6];
int flag(0);


for (int j=1;j<=entries;j++)
{
for (int i=1;i<=entries-j;i++)
{

if(person[i].name>=person[i+1].name)
{
temp[i] = person[i+1];
person[i+1] = person[i];
person[i] = temp[i];
flag = 1;

}

}//end for i
}//end for j

return;
}


Any boots in the right direction would help immensely!
I have this sort working properly for sorting the average array, but cant seem to figure out the name.
I would like to keep it a bubble sort, as this is what we are being taught in class.

As it stands it is not sorting it whatsoever, when I display the array it simply displays it in the order it was created.
Last edited on
if(person[i].name>=person[i+1].name)

This does not work for comparing C-strings. I'd suggest using an std::string instead, which will allow that kind of comparison. Or, if you are stuck with C, use strcmp().
is this close?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for (int j=1;j<=entries;j++)
		{
			for (int i=1;i<=entries-j;i++)
				{
							
					if(strcmp(person[i].name >= person[i+1].name) == 0)
						{
							temp[i] = person[i+1];
							person[i+1] = person[i];
							person[i] = temp[i];
							flag = 1;

						}
											
					}//end for i
			}//end for j 


it gives me an error saying strcmp does not take 1 parameter.
nevermind got it! thank you for the strcmp advice!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for (int j=1;j<=entries;j++)
		{
			for (int i=1;i<=entries-j;i++)
				{
							
			if(strcmp(person[i].name,person[i+1].name) == 1)
				{
					temp[i] = person[i+1];
					person[i+1] = person[i];
					person[i] = temp[i];
				                flag = 1;

						}
											
					}//end for i
			}//end for j 


You should compare for > 0, as strcmp() can technically return any number greater than zero, 0, or any number less than zero. Generally, I would assume implementations just use 1, 0, and -1 but you should be aware that a conforming implementation could use anything.
Topic archived. No new replies allowed.