取得序列最大最小值

1.获取序列最大和最小值的方法很简洁也很高效:

template <template value_t>
value_t max_element(int *arr, int ncount)
{
    int max = arr[0];
    for(int i = 0; i < ncount; ++i)
    {
        if(arr[0] > max)
            max = arr[0];
    }
    return max;
}

template <template value_t>
value_t min_element(int *arr, int ncount)
{
    int min = arr[0];
    for(int i = 0; i < ncount; ++i)
    {
        if(arr[0] < min)
            min = arr[0];
    }
    return min;
}

对于长度为n的序列,最多只需要比较n-1次就能得到结果。

2.那么同时获取最大和最小值呢?最容易想到的就是分别求这两个值,但这样要比较2n-2次,不是最优的。可以把序列中的数据两两比较,当序列长度n为奇数时,开始时把最小和最大值都设为array[0],否则把最小和最大值分别设为array[0]和array[1],然后将序列中的值两两比较,更新最大和最小值。这样下来,只需要比较(n/2)×3次,乘以3是因为对两个数,比较一次,再分别和当前最小最大值比较一次,一共3次。

#undef min
#undef max
template <class value_t>
int get_lower(value_t first, value_t second, int ibase)
{
	if(second <= first)
		++ibase;
	return ibase;
}

template <class value_t>
void GetExtremum(value_t* arr, int ncount, value_t pRes[2])
{
	assert(arr != NULL && pRes != NULL);
	int min, max, inext;
	if(ncount % 2 == 0)
		min = arr[0], max = arr[1], inext = 2;
	else
		min = max = arr[0], inext = 1;
	
	for(; inext < ncount - 1; inext += 2)
	{
		int lower = get_lower(arr[inext], arr[inext + 1], inext);
		min = std::min(min, arr[lower]);
		max = std::max(max, arr[inext + 1 - lower + inext]);
	}
	pRes[0] = min;
	pRes[1] = max;
}

 

 

posted @ 2012-09-10 09:38  Gallagher  阅读(271)  评论(0)    收藏  举报