【发布时间】:2021-06-17 06:52:09
【问题描述】:
我正在编写一个使用 Tideman 选举系统计算选举获胜者的程序。
我定义了一个名为 pair 的结构,在其中比较两个候选对象。得票最多的候选人的索引用winner表示,得票最少的候选人的索引用loser表示。
// Each pair has a winner, loser
typedef struct
{
int winner;
int loser;
}
pair;
这些对存储在pairs array
pair pairs[MAX * (MAX - 1) / 2];
我正在尝试按胜利强度的降序对这对数组进行排序(定义为winner 的投票数减去loser 的投票数)。
候选人通过他们的候选人索引被索引到vote_count,并且元素返回他们的投票数。 MAX 与候选人的最大数量有关。
int vote_count[MAX]; // where i is the index of the candidate and the return value is the number of votes.
这是我的选择排序的实现:
int max_idx; // index of element with the highest strength of victory
// one by one move boundary of unsorterd subarray
for (int i = 0; i < array_size - 1; i++)
{
max_idx = i;
for (int j = i + 1; j < array_size; j++)
{
if (vote_count[pairs[j].winner] - vote_count[pairs[j].loser] > vote_count[pairs[i].winner] - vote_count[pairs[i].loser])
{
max_idx = j;
}
}
if (max_idx != i)
{
// swap the element with the highest strength of victory with the first element
swap(&pairs[max_idx], &pairs[i]);
}
}
return;
这是我的冒泡排序实现:
for (int i = 0; i < array_size-1; i++)
{
for (int j = 0; j < array_size-i-1; j++)
{
if (vote_count[pairs[j].winner] - vote_count[pairs[j].loser] > vote_count[pairs[j+1].winner] - vote_count[pairs[j+1].loser])
{
swap(&pairs[j], &pairs[j+1]);
}
}
}
return;
每次调用swap函数:
void swap(pair *xp, pair *yp)
{
pair temp = *xp;
*xp = *yp;
*yp = temp;
}
vote_count 数组在调用另一个函数时被填充,投票:
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
// iterate through candidates
for (int i = 0; i < candidate_count; i++)
{
if (strcmp (name, candidates[i]) == 0) // if vote is for a valid candidate
{
// update rank array
ranks[rank] = i;
vote_count[i]++;
return true;
}
}
// if no candidate is found
return false;
}
选择排序或冒泡排序都不适合我,请告诉我哪里出错了。
【问题讨论】:
-
&pairs[j]是pairs + j。另外,swap是什么?我们如何知道它是否正确实施? -
调试工具有助于确认您的期望。您使用的是什么 IDE?
-
@MadPhysicist 我现在已经包含了交换功能,谢谢
-
排序看起来是正确的,但一切都取决于(a)
vote_count的大小是否足以被所有正在完成的查找索引,以及(b)swap是否正常工作。唉,我们两个都没有用于验证,因为没有提供minimal reproducible example。 -
现在您需要显示示例输入和输出,证明您确实有问题...
标签: c bubble-sort selection-sort