我正在编写一个排序算法。目前,我正在尝试用排序的元素填充一个数组。我相信这是一种冒泡排序方法。基本上,我所做的是根据 bestmatch[0] 中得分最高的分数对行进行排名,等等。对于我运行 stage3() 的每一行。
因此,从本质上讲,我获取分数(每行的分数)并将其与数组中的内容进行比较,然后根据其排名将其相加。它不工作。我的打印语句为每个输入行打印,只是打印该行的分数(前提是它不为零)。我能得到一些帮助吗?
void
stage3(double Score, line_t * linePtr) {
int j = 0;
line_t line;
size_t maxSz = MAX_LINELEN;
int scorecmp(int j, double Score, line_t * linePtr);
if (Score != 0 ) {
if (j < TOP_SCORING_MAX) {
scorecmp(j, Score, linePtr);
j++;
} /* fill up array */
else {
/* compare with last element
if greater than last element, check against
every element, moving it down while the thing
is bigger
when it is less than element, put it in that gap
*/
}
}
}
这是第二个功能
int
scorecmp(int j, double Score, line_t * linePtr) {
line_t bestmatch[TOP_SCORING_MAX];
line_t line;
if (j == 0) {
bestmatch[j].score = Score;
bestmatch[j].index = linePtr->index;
bestmatch[j].buf = linePtr->buf;
}
else if (line.score > bestmatch[j-1].score) {
bestmatch[j].score = bestmatch[j-1].score;
bestmatch[j].index = bestmatch[j-1].index;
bestmatch[j].buf = bestmatch[j-1].buf;
bestmatch[j-1].score = Score;
bestmatch[j-1].index = linePtr->score;
bestmatch[j-1].buf = linePtr->buf;
}
else if (line.score <= bestmatch[j-1].score) {
bestmatch[j].score = Score;
bestmatch[j].index = linePtr->index;
bestmatch[j].buf = linePtr->buf;
}
printf("best match = %f\n",bestmatch[0].score);
return 0;
}
完成此操作后,我需要将任何其他行与数组中得分最低的行进行比较。如果它更大,那么我需要将它与数组中的每个位置进行比较,直到它找到它的位置。
谢谢
这里是line_t的定义
typedef struct line_t
{
char* buf;
int lineLength;
int wordCount;
int index;
double score;
} line_t;
最佳答案
在您的代码中,bestmatch[] 是一个本地数组。所以,当每个步骤完成时它就过期了。
根据您的算法,应保留 bestmatch[]。
为了解决这个问题,你有两种方法。
简单的方法就是将bestmatch[]定义为全局变量。
首选方法是在特定函数(如 stage3() 或之前的调用函数)中定义 bestmath[],并将 bestmath[] 传递给 scorecmp()。
关于c - 排序算法的错误行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26033761/