使用气泡排序从类中对 2D 字符和 Int 数组进行排序

Sorting a 2D Char and Int Array from class using bubble sort?

本文关键字:排序 字符 Int 数组 2D 气泡      更新时间:2023-10-16

我正在尝试按降序对int数组和char s(来自类)进行排序。这些是学生姓名和成绩。

该类定义为:

class Student {
public:
    char name[20];
    int grades;
};

numCount是记录数的增量值。

void bubble_sort(Student theResults[], int numCount)
{
  bool swapped = true;
  while(swapped)
  {
    swapped = false;
    for(int i=1;i<numCount;i++)
    {
      if(theResults[i-1].grades < theResults[i].grades)
      {
        int tempHold = theResults[i-1].grades;
        theResults[i-1].grades = theResults[i].grades;
        theResults[i].grades = tempHold;
        swapped = true;
      }
    }
  }

我遇到的问题是int值(成绩)在循环后正确排序,但很难正确分配名称以与成绩匹配。

我使用了以下代码,但它不起作用,因为它为学生显示不正确的成绩。

char* title_temp = theResults[i-1].name;
theResults[i-1].name[20] = theResults[i].name[20];
theResults[i].name[20] = title_temp[20];
我认为

你的问题就在这里:

if(theResults[i-1].grades < theResults[i].grades)
{
    int tempHold = theResults[i-1].grades;
    theResults[i-1].grades = theResults[i].grades;
    theResults[i].grades = tempHold;
    swapped = true;
}

你真正想做的是

if(theResults[i-1].grades < theResults[i].grades)
{
    Student tempHold = theResults[i-1];
    theResults[i-1] = theResults[i];
    theResults[i] = tempHold;
    swapped = true;
}

在您更改的只是成绩值而不是名称之前,这将切换整个 Student 对象,并应生成您正在寻找的输出

你必须复制

整个char块,每次使用循环每个元素,或者你可以使用memcpy。

您也可以使用类的浅拷贝

void bubble_sort(Student theResults[], int numCount)
{

    bool swapped = true;
    while(swapped)
    {
        swapped = false;
        for(int i=1;i<numCount;i++)
        {
            if(theResults[i-1].grades < theResults[i].grades)
            {
                Student tempHold = theResults[i-1];
                theResults[i-1]= theResults[i];
                theResults[i] = tempHold;
                swapped = true;
            }
        }
    }
}

问题是你需要交换对象,成绩只需要充当指导排序的关键,试试这个:

void bubble_sort(Student theResults[], int numCount)
{
    Student tempHold;
    bool swapped = true;
    while(swapped)
    {
        swapped = false;
        for(int i=1;i<numCount;i++)
        {
            if(theResults[i-1].grades < theResults[i].grades)
            {
                tempHold = theResults[i-1]; //swap the objects, not just the grades.
                theResults[i-1]= theResults[i];
                theResults[i] = tempHold;
                swapped = true;
            }
        }
    }}

但是,如果您必须复制成员,那么除了交换成绩:

char temp[20];
strcpy(temp ,theResults[i-1].name);
strcpy(theResults[i-1].name,theResults[i].name);    
strcpy(theResults[i].name,temp);

而不是使用

    char* title_temp = theResults[i-1].name; // <-wrong
   theResults[i-1].name[20] = theResults[i].name[20];//20 is invalid index
    theResults[i].name[20] = title_temp[20]; //this is just 1 element out of the whole array

由于许多原因,这是错误的。