gpt4 book ai didi

c - 选择排序在排序后将指针保持在正确位置时出现问题

转载 作者:行者123 更新时间:2023-11-30 17:54:20 24 4
gpt4 key购买 nike

我正在尝试执行选择排序,其中我按得分最多的进球数进行排序。我有3个类别;进球、助攻、名字。我可以正确地按目标排序,并在排序后将球员的目标和助攻保留在正确的位置,但是当我尝试在排序后将名称移动到正确的位置时,它只会移动名称的第一个字母。这是我的代码。感谢您的帮助!

void sortPlayersByGoals(int* goals, int* assists, char** names, int size)
{
int lh, rh, i, tempG, tempA, tempN;
for(lh = 0; lh < size; lh++)
{
rh = lh;
for(i = lh; i < size; i++)
{
if(goals[i] > goals[rh])
{
rh = i;
}
tempG = goals[lh];
tempA = assists[lh];
tempN = *names[lh];
goals[lh] = goals[rh];
*names[lh] = *names[rh];
assists[lh] = assists[rh];
goals[rh] = tempG;
*names[rh] = tempN;
assists[rh] = tempA;
}
}

}

这是我的输出,如果这有助于显示我的问题..

Pre-Sort
Name Goals Assists
Redden 2 0
Berglund 5 2
Jackman 2 0
Stewart 4 0
Oshie 3 5
McDonald 2 4
Pietrangelo 2 7
Perron 2 6
Tarasenko 5 5
Post-Sort
Name Goals Assists
Tedden 5 5
Berglund 5 2
Sackman 4 0
Otewart 3 5
Rshie 2 0
McDonald 2 4
Pietrangelo 2 7
Perron 2 6
Jarasenko 2 0

最佳答案

void sortPlayersByGoals(int* goals, int* assists, char** names, int size)
{ /* names is an array of pointers to char */
int lh, rh, i, tempG, tempA;
char *tempN; /* a pointer to one name */
for(lh = 0; lh < size; lh++)
{
rh = lh;
for(i = lh; i < size; i++)
{
if(goals[i] > goals[rh])
{
rh = i;
}
tempG = goals[lh];
tempA = assists[lh];
tempN = names[lh]; /* names[lh] is a pointer to the name in pos lh */
goals[lh] = goals[rh];
names[lh] = names[rh]; /* swap the pointers */
assists[lh] = assists[rh];
goals[rh] = tempG;
names[rh] = tempN; /* and not just the first letter */
assists[rh] = tempA;
}
}

}

关于c - 选择排序在排序后将指针保持在正确位置时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14992252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com