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

来源:互联网 发布:热动力学分析软件 编辑:程序博客网 时间:2024/05/20 15:10
#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;
}




原创粉丝点击