如何解决在结构上实现排序算法
我正在编写一个使用 Tideman 选举系统计算选举获胜者的程序。
我定义了一个名为 pair 的结构,其中比较了两个候选对象。得票最多的候选人的索引用winner
表示,得票最少的候选人的索引用loser
表示。
// Each pair has a winner,loser
typedef struct
{
int winner;
int loser;
}
pair;
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;
void swap(pair *xp,pair *yp)
{
pair temp = *xp;
*xp = *yp;
*yp = temp;
}
// 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;
}
选择排序或冒泡排序都不适合我,请告诉我哪里出错了。
解决方法
这并不能完全回答您提出的问题,但您可以创建一个比较器函数并使用 qsort
:
/* Vote count needs to be global or file static for this to work */
int vote_count[...];
...
int compare_pair(const void *p1,const void *p2)
{
int d1 = vote_count[((const pair *)p1)->winner] - vote_count[((const pair *)p1)->loser];
int d2 = vote_count[((const pair *)p2)->winner] - vote_count[((const pair *)p2)->loser];
return d2 - d1;
}
如果你愿意,你可以把它写成一行,但会更难阅读。
排序就变成了
#include <stdlib.h>
...
qsort(pairs,MAX * (MAX - 1) / 2,sizeof(pair),compare_pair);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。