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


// 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 ;
}
posted @ 2011-04-17 09:18  walfud  阅读(979)  评论(0编辑  收藏  举报