【问题标题】:Array Structure sorting数组结构排序
【发布时间】:2013-11-22 04:10:40
【问题描述】:

我无法对这段代码进行排序,呃

任何见解都会是巨大的

结构:

// Test Score

struct testData  //declare testScore

{

int score ;// score of each student 
string student; // Student name 

};

//  Functions prototypes

void sSort(struct testData * , int);
void displaySorts(struct testData *, int);
double avgScore(double);

这是我最麻烦的部分

排序代码 // 排序函数

void  sSort(struct testData *gradDat, int SIZE)
{
int scan, minIndex, minValue;

for ( scan=0 ; scan < (SIZE - 1); scan++)
{
    minIndex = scan;
    minValue = (*(gradDat+ scan)).score;

    for(int index = scan + 1; index < SIZE; index++)
    {
        if ((*(gradDat + scan)).score < minValue)
         { 
            minValue = (*(gradDat + scan)).score;
            minIndex = index;
         }

    }
    //gradDat[minIndex] = *(gradDat + scan);
    //(*(gradDat + scan)).score = minValue;

    testData temp = gradDat[scan];
    gradDat[minIndex] = gradDat[scan];
    gradDat[scan] = temp;
 }

// Check sort - bu hiding now
for (int count = 0; count < SIZE ; count++)
{
    cout << (*(gradDat + count)).student <<" "<< (*(gradDat + count)).score;
    cout << endl;
}  


}

我在另一篇文章中更改了代码,但没有帮助

有什么想法吗?

【问题讨论】:

  • 你遇到了什么问题?你到底想做什么?

标签: arrays pointers structure


【解决方案1】:

您似乎弄错了循环索引。内循环应该是:

for(int index = scan + 1; index < SIZE; index++)
{
    if ((*(gradDat + index)).score < minValue)
     { 
        minValue = (*(gradDat + index)).score;
        minIndex = index;
     }

}

您正在为该循环使用index,而不是scan

而且在交换值时也会出错:

testData temp = gradDat[minIndex];
gradDat[minIndex] = gradDat[scan];
gradDat[scan] = temp;

PS:也许您想考虑使用数组表示法使代码更具可读性:gradDat[index].score

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多