#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;
}