编程语言
首页 > 编程语言> > (JAVA)对象数组的排序

(JAVA)对象数组的排序

作者:互联网

题目:

        有20 个学生 , 学号依次是 1-20 , 成绩分数为随机数,请利用冒泡排序,按学生成绩从低到高进行排序。

        

//错误的写法
for(int i  = 0 ; i<stus.length-1 ; i++)
{
    for(int j  = 0 ;j<stus.length - 1 - i ; j++)
    {
        if(stus[j].score>stus[j+1].score)
        {
            int t = stus[j].score;
            stus[j].score = stus[j+1].score;
            stus[j+1].score = t ;
        }
    }
}

注意:

        此时的交换算法  只是将学生的分数进行了交换 , 可以这样理解 将 张 三 的分数与李 四的分数进行了交换,并不是交换了两个学生的排名 。

稍加思考,我们只需将 stus 数组元素的位置进行交换即可。

//错误的写法
for(int i  = 0 ; i<stus.length-1 ; i++)
{
    for(int j  = 0 ;j<stus.length - 1 - i ; j++)
    {
        if(stus[j].score>stus[j+1].score)
        {
            Student t = stus[j];
            stus[j] = stus[j+1];
            stus[j+1] = t ;
        }
    }
}

要点:

        通过比较学生的分数, 将学生的位置(排名)进行交换 。

标签:分数,stus,JAVA,int,交换,学生,score,数组,排序
来源: https://blog.csdn.net/zcs18338992657/article/details/121529971