一个数组中同时找到最大/最小值

 
  

// main.cpp
// Find minimum & maximum in one array at one time

#include
< iostream >
#include
< utility >
using namespace std ;

void PairFind( int arr[], size_t len, size_t begin, int & mi, int & ma)
{
for ( int i = begin ;i + 1 < len ;i += 2 )
{
if (arr[i] < arr[i + 1 ])
{
mi
= (arr[i] < mi ? arr[i] : mi) ;
ma
= (arr[i + 1 ] > ma ? arr[i + 1 ] : ma) ;
}
else // arr[i] >= arr[i+1]
{
mi
= (arr[i + 1 ] < mi ? arr[i + 1 ] : mi) ;
ma
= (arr[i] > ma ? arr[i] : ma) ;
}
// if
} // for
}

pair
< int , int > MinMax( int arr[], size_t len)
{
int minimum = 0 ;
int maximum = 0 ;

  
// It is better to split the odd case & even case. Good idea !
if ( 1 == len % 2 ) // Odd
{
minimum
= maximum = arr[ 0 ] ;
PairFind(arr, len,
1 , minimum, maximum) ;
}
else // Even number
{
minimum
= arr[ 0 ] ;
maximum
= arr[ 1 ] ;
PairFind(arr, len,
2 , minimum, maximum) ;
}
// if

return pair < int , int > (minimum, maximum) ;
}

int arr_even[] = { 2 , 4 , 9 , 6 , 7 , 1 , 0 , 3 , 8 , 5 } ;
int arr_odd[] = { 2 , 4 , 9 , 6 , 7 , 1 , 0 , 3 , 8 , 5 , 7 } ;

int main()
{
pair
< int , int > miMa_even = MinMax(arr_even, sizeof (arr_even) / sizeof (arr_even[ 0 ])) ;\
cout
<< " minimum is : " << miMa_even.first << endl ;
cout
<< " maximum is : " << miMa_even.second << endl ;

cout
<< endl ;

pair
< int , int > miMa_odd = MinMax(arr_odd, sizeof (arr_odd) / sizeof (arr_odd[ 0 ])) ;
cout
<< " minimum is : " << miMa_odd.first << endl ;
cout
<< " maximum is : " << miMa_odd.second << endl ;

return 0 ;
}

转载于:https://www.cnblogs.com/walfud/archive/2011/04/17/2018687.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值