📌  相关文章
📜  C程序查找数组的最大和最小元素

📅  最后修改于: 2021-05-28 05:11:10             🧑  作者: Mango

给定N个整数的数组arr [] ,任务是编写C程序以迭代和递归的方式找到给定数组的最大和最小元素。

例子:

方法:

  1. maxEminE为变量,以存储数组的最小和最大元素。
  2. minE初始化为INT_MAX,将maxE初始化为INT_MIN。
  3. 遍历给定的数组arr []。
  4. 如果当前元素小于minE ,则将minE更新为当前元素。
  5. 如果当前元素大于maxE ,则将maxE更新为当前元素。
  6. 对数组中的元素重复上述两个步骤。

下面是上述方法的实现:

Iterative Approach
// C program for the above approach
#include 
#include 
  
// Function to find the minimum and
// maximum element of the array
void findMinimumMaximum(int arr[], int N)
{
    int i;
  
    // variable to store the minimum
    // and maximum element
    int minE = INT_MAX, maxE = INT_MIN;
  
    // Traverse the given array
    for (i = 0; i < N; i++) {
  
        // If current element is smaller
        // than minE then update it
        if (arr[i] < minE) {
            minE = arr[i];
        }
  
        // If current element is greater
        // than maxE then update it
        if (arr[i] > maxE) {
            maxE = arr[i];
        }
    }
  
    // Print the minimum and maximum element
    printf("The minimum element is %d", minE);
    printf("\n");
    printf("The maximum element is %d", maxE);
  
    return;
}
  
// Driver Code
int main()
{
  
    // Given array
    int arr[] = { 1, 2, 4, -1 };
  
    // length of the array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    findMinimumMaximum(arr, N);
  
    return 0;
}


Recursive Approach
// C program for the above approach
#include 
#include 
  
// Recursive function to find the minimum
// and the maximum element of the array
void recursiveMinMax(int arr[], int N,
                     int* minE, int* maxE)
{
    // Base Case
    if (N < 0) {
        return;
    }
  
    // If current element is smaller
    // than minE then update it
    if (arr[N] < *minE) {
        *minE = arr[N];
    }
  
    // If current element is greater
    // than maxE then update it
    if (arr[N] > *maxE) {
        *maxE = arr[N];
    }
  
    // Recursive call for next iteration
    recursiveMinMax(arr, N - 1, minE, maxE);
}
  
// Function to find the minimum and
// maximum element of the array
void findMinimumMaximum(int arr[], int N)
{
    int i;
  
    // variable to store the minimum
    // and maximum element
    int minE = INT_MAX, maxE = INT_MIN;
  
    // Recursive Function to find
    // minimum & maximum element
    recursiveMinMax(arr, N - 1, &minE, &maxE);
  
    // Print the minimum and maximum element
    printf("The minimum element is %d", minE);
    printf("\n");
    printf("The maximum element is %d", maxE);
  
    return;
}
  
// Driver Code
int main()
{
  
    // Given array
    int arr[] = { 1, 2, 4, -1 };
  
    // length of the array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    findMinimumMaximum(arr, N);
    return 0;
}


输出:
The minimum element is -1
The maximum element is 4

时间复杂度: O(N) ,其中N是给定数组中元素的数量。

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。