选择排序逻辑错误
我正在使用选择排序对板球队的名单进行排序。
首先重复一个名称 3 次后,排序就会起作用,这会从我正在排序的数组中消除其他两个名称。
从数组输入(按顺序):
Clarke Watson Beer Copeland Haddin Harris Hughes Hussey Johnson Khawaja Lyon Marsh Pattinson Ponting Siddle Warner
排序数组后输出:
Beer Beer Beer Copeland Haddin Harris Hughes Hussey Johnson Khawaja Lyon Marsh Pattinson Ponting
代码:
void sort_names (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);
}
}
}
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_names (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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的这段代码将无法正确交换条目:
第一行将指向“pos”玩家名称的指针保存到
temp
- 不名字本身。然后第一个 strcpy 覆盖它 - 它丢失了。 (第二个 strcpy 只是将相同的字符串复制回原来的位置。)这就是为什么您会看到首先排序的项目多次出现的原因。This bit of your code won't swap entries correctly:
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.