I'm asked to write an code, to do insertion sorting to sort GPA from highest to lowest. This is my code, and it's printing for me the same entered list :( there is no changes happens! so, the student with lowest gpa should be sorted to the end of the array. The output is only sort the GPA with out the ID. The point is here i need to sort Students by their GPA's and for sure their ID'S next to it.
#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
Added this answer to keep this simple and easy to comprehend instead of stating from 0th index, I started with N-1 index, and compare with right most of elements, in short just opposite of generic insertion sort.
#include <stdio.h>
typedef struct
{
int ID;
float GPA;
}STUDENT;
void InsertionSortModified(STUDENT *StuAry,int N)
{
int i, key, j;
STUDENT pnt;
for (i = N-2; i >= 0; i--) {
pnt = StuAry[i];
key = StuAry[i].GPA;
j = i + 1;
while (j < N && StuAry[j].GPA > key) {
StuAry[j - 1] = StuAry[j];
j = j + 1;
}
StuAry[j - 1] = pnt;
}
}
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}, {5, 12.21}, {6, 98}};
int N=6;
printf("Before Sorting: \n");
printArray(StuAry,N);
InsertionSortModified(StuAry,N);
printf("After Sorting: \n");
printArray(StuAry,N);
return 0;
}