博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
// 2_9.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <cassert>

#define INT_MIN -100000

//最大值和最小值
void min_max(int * arr, size_t len, int & min, int &max)
{
	assert(arr);
	assert(len>0);
	int start = 0;
	if(len%2 ==0)
	{
		if(arr[0]>arr[1])
		{
			min=arr[1];
			max=arr[0];
		}
		else
		{
			min=arr[0];
			max=arr[1];
		}
		start=2;
	}
	else
	{
		min=arr[0];
		max=arr[1];
		start = 1;
	}
	for(;start<len;start+=2)
	{
		if(arr[start]>arr[start+1])
		{
			if(arr[start]>max)
				max = arr[start];
			if(arr[start+1]<min)
				min = arr[start+1];
		}
		else
		{
			if(arr[start+1]>max)
				max = arr[start+1];
			if(arr[start]<min)
				min = arr[start];
		}
	}

}

//最大值和次大值,递归实现
void max_secondMax(int * arr, int left, int right, int & max, int &max2)
{
	if(right == left)
	{
		max = arr[left];
		max2 = INT_MIN;
		return;
	}
	else if(right - left == 1)
	{
		if(arr[right] > arr[left])
		{
			max = arr[right];
			max2 = arr[left];
			return;
		}
		else
		{
			max = arr[left];
			max2 = arr[right];
			return;
		}
	}
	int lmax, lmax2;
	int rmax, rmax2;
	max_secondMax(arr, left, left+(right-left)/2,lmax,lmax2);
	max_secondMax(arr, left+(right-left)/2+1, right,rmax,rmax2);

	if(lmax>rmax)
	{
		max = lmax;
		if(lmax2 > rmax)
			max2 = lmax2;
		else
			max2 = rmax;
	}
	else
	{
		max = rmax;
		if(rmax2 > lmax)
			max2 = rmax2;
		else
			max2 = lmax;
	}

}

int _tmain(int argc, _TCHAR* argv[])
{
	int arr[5] = {2,3,102,4,100};
	int min,max;
	min_max(arr,5,min,max);

	printf("max:%d,min:%d\n",max,min);

	int max2;
	max_secondMax(arr,0,4,max,max2);

	printf("max:%d,second max:%d\n",max,max2);

	
	return 0;
}