C语言 编写一个函数,用于查找结构数组中的前 5 个最大值



找到结构数组中的前 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  %dn", people[i].name, people[i].number);
}

但是,自其字符类型以来,我在第二次交换时收到错误消息。我应该如何解决这个问题,或者还有什么可以实现这一目标?

只需对数组进行排序,然后获取排序数组的 5 个第一个/最后一个(取决于排序顺序(条目。

第一个定义一个比较函数:

#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;
}

2nd 使用标准 C 函数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);
  }
}

从 OP 的代码开始,只需交换结构即可。 @BLUEPIXY。OP的代码只需要一个小的更改。

数组不能与赋值一起复制,但可以分配对象(如struct info(。

int i, j, k=5;
//move maximum `k` numbers to the front of the array
for (i=0; i<k; i++) {
  int max=i;
  for (j=i+1; j<10; j++) {
    if (people[i].number > people[max].number) {
      max=j;
    }
  }
  //swap info
  struct info temp = people[i];
  people[i] = people[max];
  people[max] = temp;
}
for (i=0; i<k; i++) {
  printf("%s  %dn", people[i].name, people[i].number);
}

最简单和最通用的方法可能是首先对people数组进行排序。完成此操作后,只需选择前五个元素即可。

最好的方法是根据数字属性 iso 单个交换对数组人员进行排序。

如果你想继续使用当前的方法,请使用 strcpy 函数 iso"=" 运算符作为名称

与其跟踪总共 10 个索引中的 5 个,排序对我来说似乎更好。您可以使用 qsort 对 10 个元素进行排序,然后选择前 5 个元素。

 int cmp(void *a,void *b)
 {
   struct info as=*((struct info*)a);
   struct info bs=*((struct info*)b)
   return bs.number-as.number;  //sorting in descending order
 }

然后

    qsort(people,10,sizeof people[0],cmp);

最新更新