如何在数组中找到最大和最小数字的位置?

时间:2018-03-18 12:02:26

标签: c arrays position max min

int A[5] = {2, 2, 1, 4, 1};    
int max = A[0], min = A[0];
int k,l;

for (i = 0; i < 5; i++) {
    if (A[i] >= max) {
        max = A[i];
        k = i;
    }
}

for (j = 0; j < 5; j++) {
    if (A[j] <= min) {
        min = A[j];
        l = j;
    }
}

printf("densely is: %d ", k);
printf("\n");
printf("loosely is: %d ", l);

程序会将denselymax)的位置打印为3。 它将looselymin)的位置打印为4。 但looselymin)职位的正确答案应为24。 就我而言,max号码为4,因此排名应为3(从0开始计算)。 min号码为1,因此排名应为24。 现在,我的代码只显示min号码的一个位置:4。 它应该打印两个位置:24

我想打印maxmin个数字的所有位置。

1 个答案:

答案 0 :(得分:1)

这实际上是非常好的问题。解决方案的关键是在数组min中找到maxA值。这部分已经完成并运作良好。这里唯一的改进是从索引1开始,从=>=比较中删除<=。 缺少的部分是记住minmax的所有索引。

一次通过很难做到。您可以一次性完成的工作是查找minmax

在第二次传递中有minmax之后,您可以在名为max的其他索引表中标记minmaximums的所有索引位置和minimums。 (因为我想打印这些值,我有两个独立的循环。)

解决方案非常简单:

#include <stdio.h>

// Find all minimums and all maximums in the array A
// Find and remember where `max` and `min` values were in the array A
// The algorithm is symmetrical for minimum and maximum 

int main(void)
{             // 0  1  2  3  4 
    int A[5] = { 2, 2, 1, 4, 1};    

    int maximums[5] = {0};  // we keep max positions here
    int minimums[5] = {0};  // we keep min positions here

    int max = A[0];  // we assume max at index 0
    int min = A[0];  // we assume min at index 0

    for (int i = 1; i < 5; i++) {       // we can start from index 1 because of the above assumption
        if (A[i] > max) max = A[i];     // densely 
        if (A[i] < min) min = A[i];     // loosely
    }

    // Find the all elements equal to `max` and `min` 
    // and register them in `maximums` and `minimums` arrays

    // Print the results:
    printf("max value is: %d and it occurs at the following index(es):\n", max);         
    for (int i = 0; i < 5; i++) {

        if (A[i] == max){ 
            maximums[i] = 1;   // mark this index as maximum being here
            printf("%d ", i);
        }
    }

    printf("\nmin value is: %d and it occurs at the following index(es):\n", min );   
    for (int i = 0; i < 5; i++) {

        if (A[i] == min){ 
            minimums[i] = 1;   // mark this index as minimum being here
            printf("%d ", i);
        }    
    }

    // At this moment we not only printed the results 
    // but the array minimums and maximums remember where the `min` and `max` were.

    return 0;
}

输出:

max value is: 4 and it occurs at the following index(es):                                                                                       
3                                                                                                                                               
min value is: 1 and it occurs at the following index(es):                                                                                       
2 4