首页 > 解决方案 > 怎么能做插入排序,但要打印从最高到最低的 GPA?

问题描述

我被要求编写代码,进行插入排序以将 GPA 从最高到最低排序。这是我的代码,它为我打印了相同的输入列表:(没有发生任何变化!所以,gpa最低的学生应该被排序到数组的末尾。输出只是对没有ID的GPA进行排序. 重点是我需要按学生的 GPA 排序,并确保他们的 ID 在旁边。

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef struct
{
   int ID;
   float GPA;
}STUDENT;

// method that sorts the array in descending order of GPA
void InsertionSortModified(STUDENT *StuAry,int N)
{
    int walk;
    float temp;
    bool located;

    for(int current =1; current <= N; current++){
        located=false;
        temp = StuAry[current].GPA;

        for(walk = current-1; walk>=0 && !located;)
        {
           if( temp > StuAry[walk].GPA)
           {
              StuAry[walk+1].GPA = StuAry[walk].GPA;
              walk --;
           }
            else
                located=true;
            StuAry[walk+1].GPA=temp;
        }
    }
}


void printArray(STUDENT *StuAry,int N)
{
   for(int i=0;i<N;i++)
       printf("%d %.2f\n",StuAry[i].ID,StuAry[i].GPA);
   printf("\n");
}

// testing main method
int main()
{
   STUDENT StuAry[]={{1,65.2},{2,75.3},{3,34.5},{4,99.9}};
   int N=4;
   printf("Before Sorting: \n");
   printArray(StuAry,N);
   InsertionSortModified(StuAry,N);
   printf("After Sorting: \n");
   printArray(StuAry,N);

   return 0;

}

//Now the problem is the output:
//Before sorting:
//1 56.20
//2 75.30
//3 34.50 
//4 99.90

//After sorting: //Notice her the integer(ID) it's not changing

//1 99.90
//2 75.30
//3 65.20
//4 34.50

标签: csortingstructinsertion-sortfunction-definition

解决方案


步行 >=0

  • 你的温度应该是一个浮点数

推荐阅读