在C ++中使用二维数组的插入排序函数?

时间:2016-01-09 23:40:12

标签: c++ arrays sorting

我正在做的一个函数使用插入排序来处理具有2行和12列的二维数组。第一行是学生ID,因此总共有12名学生。第二行为每个学生提供相应的GPA。我不确定如何提出插入排序以按升序对GPA数字进行排序。任何帮助都是极好的!

到目前为止,我有这个。

void insertionSort(double avg[][COLS])
{
int current = 1;
int last = COLS - 1;
int temp;
int walker;
int row = 1;

while (current <= last)
{
    temp = avg[row][current];
    walker = current - 1;
    while (walker >= 0
        && temp < avg[row][walker])
    {
        avg[row][walker+1] = avg[row][walker];
        walker = walker - 1;
    }

    avg[row][walker+1] = temp;
    current = current + 1;
}

1 个答案:

答案 0 :(得分:1)

你的问题是temp变量被声明为一个int它应该加倍你也应该交换ID

void insertionSort(double avg[][COLS])
{
    int current = 1;
    int last = COLS - 1;
    double temp;//this was an int
    int walker;
    int row = 1;

    while (current <= last)
    {
        temp = avg[row][current];
        walker = current - 1;
        while (walker >= 0
                && temp < avg[row][walker])
        {
            avg[row][walker+1] = avg[row][walker];
            avg[row-1][walker+1] = avg[row-1][walker];//swap the id of two students
            walker = walker - 1;
        }

        avg[row][walker+1] = temp;
        avg[row-1][walker+1] = temp;
        current = current + 1;
    }
}