输入N个数组,求出其最大最小值及计算复杂度

这是一个C语言程序,用于输入N个整数数组,找出数组中的最小值和最大值,同时计算比较次数。程序首先初始化最小值和最大值为数组的第一个元素,然后通过迭代数组,每次比较相邻两个元素,更新最小值和最大值。最后,如果数组长度为奇数,还会检查最后一个元素。程序使用动态内存分配,并在结束时释放。输出包括最小值、最大值以及比较次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int iter = 0;
    int cnt = 0;
    int N;
    printf("Input the array length N: ");
    scanf("%d", &N);
    printf("Please input %d (int) number:\n ",N);
    int *arr = (int *) malloc(N * sizeof(int));
    for( int i = 0; i < N; i++)
    scanf("%d", &arr[i]);

    for(iter = 0; iter < N-1  ; iter += 2)
    {
        if(++cnt && arr[iter] > arr[iter + 1] )
        {
            int temp = arr[iter];
            arr[iter] = arr[iter + 1];
            arr[iter + 1] = temp;
        }
    }
    int myMin = arr[0];
    for(iter = 2; iter < N ; iter += 2)
    {
        if(++cnt && arr[iter] < myMin)
        {
            myMin = arr[iter];
        }
    }
    int myMax = arr[1];
    for(iter = 3; iter < N; iter += 2)
    {
        if(++cnt && arr[iter] > myMax)
        {
            myMax = arr[iter];
        }
    }

    if(N % 2 != 0 && ++cnt && myMax < arr[N - 1]) myMax = arr[N - 1];

  free(arr);

    printf("min is %d\n", myMin);

    printf("max is %d\n", myMax);
    printf("compare times is %d", cnt);// 3*N/2
    return 0;

}

//不交换数组的方法

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int iter = 0;
    int cnt = 0;
    int N;
    printf("Input the array length N: ");
    scanf("%d", &N);
    printf("Please input %d (int) number:\n ",N);
    int *arr = (int *) malloc(N * sizeof(int));
     for( int i = 0; i < N; i++)
     scanf("%d", &arr[i]);
     int myMin ,myMax;
     myMin =myMax=arr[0];
     for(iter = 0; iter < N-1  ; iter +=2)
      {  
        if( ++cnt&&arr[iter]>arr[iter + 1]) 
         {
           if ( ++cnt&&arr[iter+1]< myMin)
               myMin = arr[iter+1];
           if(++cnt&&arr[iter ] >myMax)
               myMax = arr[iter];  
        }else
          {
            if( ++cnt&&arr[iter]< myMin)
               myMin = arr[iter];
           if(++cnt&&arr[iter + 1] >myMax)
               myMax = arr[iter+1];    
        }
     }

    if(N % 2 != 0 && ++cnt && myMax < arr[N - 1]) myMax = arr[N - 1];
    free(arr);
    printf("min is %d\n", myMin);
    printf("max is %d\n", myMax);
    printf("compare times is %d", cnt);
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值