找到结构数组中的前 5 个最大值(用于 C 编程)? 我有如下结构数组:
struct info {
char name[100];
int number;
}
struct info people[10]
char name[100] 中是人名(最多 10 个),他们在 int balance 中有相应的值:
Jane 10
John 40
Harry 16
Eva -5
...
直到达到 10 人。
如何找到并打印出数字最高的 5 个人?
即:
John 40
Harry 16
Jane 10
...
我试过下面的代码:
int i,j, k=5, max, temp;
//move maximum 5 numbers to the front of the array
for (i=0; i<k; i++) {
max=i;
for (j=i+1; j<10; j++) {
if (people[i].number>people[max].number) {
max=j;
}
}
//swap numbers
temp=people[i].number;
people[i].number=people[max].number;
people[max].number=temp;
//swap names to match swapped numbers so they correspond
temp=people[i].name;
people[i].name=people[max].name;
people[max]=temp;
}
for (i=0; i<k; i++) {
printf("%s %d\n", people[i].name, people[i].number);
}
但是,由于其 char 类型,我在第二次交换时收到错误消息。我应该如何解决这个问题,或者还有什么可以解决这个问题?
最佳答案
只需对数组进行排序,然后取已排序数组的第一个/最后一个(取决于排序顺序)条目。
首先定义一个比较函数:
#include <stdlib.h> /* for qsort() */
#include <stdio.h> /* for printf() */
struct info
{
char name[100];
int number;
};
int cmp_struct_info_desc(const void * pv1, const void * pv2)
{
const struct info * pi1 = pv1;
const struct info * pi2 = pv2;
return pi2->number - pi1->number;
}
第二次使用 Standard C function qsort()
.
struct info people[] = {
... /* initialise array people here ... */
}
int main(void)
{
size_t number_of_array_elements = sizeof people/sizeof *people;
qsort(people, number_of_array_elements, sizeof *people, cmp_struct_info_desc);
for (size_t s = 0; s < number_of_array_elements; ++s)
{
printf("%zu. = {%d, '%s'}\n", s, people[s].number, people[s].name);
}
}
关于c - 编写一个函数来查找结构数组中的前 5 个最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43371480/