I am using the selection sort to sort a list of names from a cricket team.
The sort works after first repeating a name 3 times which eliminates two other names from the array I am sorting.
Input from array (in order):
Clarke Watson Beer Copeland Haddin Harris Hughes Hussey Johnson Khawaja Lyon Marsh Pattinson Ponting Siddle Warner
Output after sorting array:
Beer Beer Beer Copeland Haddin Harris Hughes Hussey Johnson Khawaja Lyon Marsh Pattinson Ponting
Code:
void sort_name开发者_运维百科s (Team_t player[]) {
int pos;
int min;
int i, str_check;
char *temp = NULL;
for (pos = 0; pos < MAX_PLYR; pos++) {
min = pos;
for (i = (pos + 1); i < MAX_PLYR; i++) {
str_check = strcmp(player[i].pname, player[min].pname);
if (str_check < 0) {
min = i;
}
}
if (min != pos) {
temp = player[pos].pname;
strcpy(player[pos].pname, player[min].pname);
strcpy(player[min].pname, temp);
}
}
}
This bit of your code won't swap entries correctly:
temp = player[pos].pname;
strcpy(player[pos].pname, player[min].pname);
strcpy(player[min].pname, temp);
The first line saves a pointer to the 'pos' player's name to temp
- not the name itself. Then the first strcpy overwrites it - it is lost. (The second strcpy merely copies the same string back to where it already was.) That's why you see the item that would sort first sprouting up more than once.
精彩评论