c - 编写一个函数来查找结构数组中的前 5 个最大值?

标签 c arrays structure

找到结构数组中的前 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/

相关文章:

c - 在使用 scanf 读取的 char 变量中添加两个数字

arrays - 在 let 常量数组中初始化和存储一个对象的 N 个实例?

java - 使用状态模式解耦状态

c - __always_inline 和 inline 之间的区别

c - 在 switch 语句中使用输入默认值时,程序陷入无限循环

javascript - typescript 或 JavaScript : searching for multiple words

javascript - 使用带有对象数组的 setState react 不更新状态

c - C中的结构,检查点是否在圆圈内

c++ - 错误与 'operator=' 不匹配(操作数类型为 'Person' 和 'Person*' )

c - 打开文本文件并在 C 中搜索字符串后无输出