最大的两个数

题目截图:

 

思路:

  先对每列四个数按数值大小逆序排序,然后对最大的两个数按索引顺序排序即可。中间用到 qsort 函数,详细用法见另一篇博客

 

代码如下:

 1 /*
 2     最大的两个数 
 3 */
 4 
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <math.h>
 8 #include <stdlib.h>
 9 #include <time.h>
10 #include <stdbool.h>
11 
12 // 结点结构体 
13 typedef struct {
14     int data;                    // 数据 
15     int index;                    // 数组下标 
16 } node;
17 
18 // 按数据大小逆序排序 
19 int cmp1(const void* a, const void* b) {
20     node* c = (node*)a;
21     node* d = (node*)b;
22     return d->data - c->data;
23 }
24 
25 // 按原数组下标大小顺序排序 
26 int cmp2(const void* a, const void* b) {
27     node* c = (node*)a;
28     node* d = (node*)b;
29     return c->index - d->index;
30 }
31 
32 int main() {
33     int array[4][5];            // 存储矩阵 
34     int a[2][5];                // 存储每列最大的两个数 
35     node l[4];                    // 存储每列四个结点 
36     while(1) {
37         int i, j;
38         for(i=0; i<4; ++i) {    // 输入矩阵 
39             for(j=0; j<5; ++j) {
40                 if(scanf("%d", &array[i][j]) == EOF) {
41                     return 0;
42                 }
43             }
44         }
45         for(j=0; j<5; ++j) {    
46             for(i=0; i<4; ++i) {    // 初始化每列结点 
47                 l[i].data = array[i][j];
48                 l[i].index = i;
49             }
50             // 排序 
51             qsort(l, 4, sizeof(l[0]), cmp1);
52             qsort(l, 2, sizeof(l[0]), cmp2);
53             for(i=0; i<2; ++i) {    // 存储每列最大的两个数 
54                 a[i][j] = l[i].data;
55             }
56         }
57         for(i=0; i<2; ++i) {        // 按要求输出 
58             for(j=0; j<5; ++j) {
59                 printf("%d ", a[i][j]);
60             }
61             printf("\n");
62         }
63     }
64 
65     return 0;
66 }

 

转载于:https://www.cnblogs.com/coderJiebao/p/HustTest11.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值