我正在尝试在我的C ++程序中实现插入排序,以根据他们的测试分数按升序对学生的姓名和他们的考试成绩进行排序。名称和测试分数是用户定义的。就构建我的程序而言,我没有错误。程序也运行并正确计算平均值,但插入排序不会对用户输入的信息进行排序。我使用一组结构设置为指针,由用户动态分配以保存每个学生的信息,并且必须使用指针而不是数组索引。任何有关修复我的程序的插入排序的建议和帮助将非常感激。另外,我想知道我是否正确使用指针和指针表示法。
struct Pair
{
string names;
int testscores;
};
//Function prototypes//
void sorting(Pair*,int);
void Swap(int,int,string,string);
int getAVG(Pair*,int);
int main()
{
Pair *NS;
int average, num_test;
cout<<"How many test scores would you like to enter? ";
cin>>num_test;
while(num_test<0||!cin)
{
cout<<"**Invalid entry** Amount of test scores cannot be written/typed in letters.\nPlease enter valid amount of test scores: ";
cin>>num_test;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
if(num_test>0)
{NS=new Pair[num_test];}
if (NS == NULL)
{
cout<<"Memory allocation error.";
exit(1);
}
for(int i=0;i<num_test;i++)
{
cout<<"\nEnter name of student "<<i+1<< " and their test score:";
cin>>(NS+i)->names>>(NS+i)->testscores;
while((NS+i)->testscores<0 || !cin)
{
cout<<" **Invalid Entry**\n Test scores entered cannot be letters or negative numbers. Please enter valid test score.\n";
cin>>(NS+i)->testscores;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
}
sorting(NS,num_test);
cout<<"\n**Test Scores in ascending order**\n\n";
for(int k=0; k<num_test; k++)
{
cout<<(NS+k)->names<<": "<<(NS+k)->testscores<<"\n";
}
average=getAVG(NS,num_test);
cout<<"\n\nAverage test score: "<<average<<endl;
delete[] NS;
NS=0;
return 0;
}
//This is the sorting function and swap function portion of my program//
void sorting (Pair *s_ptr, int Length)
{
int j;
for(int count=1; count <Length; count++)
{
for(j=count; j>0 && ((s_ptr+j-1)->testscores)>((s_ptr+j)->testscores);j--)
{
Swap(((s_ptr+j-1)->testscores),((s_ptr+j)->testscores),((s_ptr+j-1)->names),((s_ptr+j)->names));
}
}}
void Swap( int index1, int index2, string name1, string name2)
{
int temp=index1;
index1=index2;
index2=temp;
string N_temp=name1;
name1=name2;
name2=N_temp;
}