当前尝试使用气泡排序对数组进行排序,然后获取平均值,但返回的平均值是错误的

Currently trying to sort an array using bubble sort and then getting the average but the average that returns is wrong.

本文关键字:平均值 排序 然后 获取 错误 返回 数组 气泡      更新时间:2023-10-16
else if (order == "average") {
    int average = 0;
    int temp;
    for (int i = 0; i < NO_TEAMS; i++)
    {
        for (int j = 0; j < NO_TEAMS - 1; j++)
        {
            if (ptr[yearIndex].teams[j].fum < ptr[yearIndex].teams[j + 1].fum) {
                temp = ptr[yearIndex].teams[i].fum;
                ptr[yearIndex].teams[j].fum = ptr[yearIndex].teams[j + 1].fum;
                ptr[yearIndex].teams[j + 1].lost = temp;
            }
        }
    }
    for (int i = 0; i < NO_TEAMS; i++) {
        average = average + ptr[yearIndex].teams[i].fum;
    }

对于此代码,平均值返回 26。但是,如果我消除气泡排序代码,则平均值返回 20(这是正确的平均值)。如何解决此问题?

显然,您没有正确交换项目。问题出在以下三行:

temp = ptr[yearIndex].teams[i].fum;
ptr[yearIndex].teams[j].fum = ptr[yearIndex].teams[j + 1].fum;
ptr[yearIndex].teams[j + 1].lost = temp

将第一行更改为索引 j ,而不是i

temp = ptr[yearIndex].teams[j].fum;