排序结构不起作用

时间:2014-04-07 09:07:34

标签: c sorting struct

您好我正在尝试排序结构但由于某种原因它不起作用所以我会很高兴如果你可以帮我解决问题。感谢。

(N = 6)

我的排序 -

for(i = 0; i < N-1; i++) 
{  
    for(j = i + 1; j < N; j++)
    {    
        if(basketball[i].points_number > basketball[i].points_number) 
        {     
            temp = basketball[i].points_number; 
            basketball[i] = basketball[j];   
            basketball[j].points_number = temp;   
        }
    }
}

我的结构 -

struct player
{
    char name[20]; 
    float height;
    float points_number; 
    int vest_number; 
};

5 个答案:

答案 0 :(得分:1)

你有

basketball[i] = basketball[i];

即,正在用自己覆盖相同的条目。我想,应该阅读

basketball[i] = basketball[j];  // Note the "j" on the right-hand side of the assignment

答案 1 :(得分:1)

首先,你有

if(basketball[i].points_number > basketball[i].points_number)

你想要的地方(注意j

if(basketball[j].points_number > basketball[i].points_number)

然后,您必须交换整个结构,而不仅仅是points_number结构,因此您将拥有

struct player temp = basketball[i]; 
basketball[i] = basketball[j];   
basketball[j] = temp;  

答案 2 :(得分:0)

for(i = 0; i < N-1; i++) 
{  
    for(j = i + 1; j < N; j++)
    {    
        if(basketball[i].points_number > basketball[j].points_number) 
        {     
            temp = basketball[i]; 
            basketball[i] = basketball[j];   
            basketball[j] = temp;   
        }
    }
}

答案 3 :(得分:0)

请检查此行:

if(basketball[i].points_number > basketball[i].points_number) 

在这里你要比较相同的值,因为在篮球[i]中检查了两个ith元素。它应该是:

if(basketball[i].points_number > basketball[j].points_number) 

答案 4 :(得分:0)

你需要交换玩家的结构,但是只保存在临时变量中。应该是

        struct player temp;
        temp = basketball[i]; 
        basketball[i] = basketball[j];   
        basketball[j] = temp;