`
easyhaohao
  • 浏览: 13536 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

最大数与最小数

 
阅读更多

public class MaxAndMin {

	
	
	public static void main(String []args)
	{
		
		int a[] =  {1,1,1,1,1,1,1,1};	
		findSecondMax(a);
	}
	
	
	//找出数组中最大的跟最小的
	public static void method1(int a[])
	{
		for(int i=0;i<a.length;i=i+2)
		{
			
			if(i==a.length-1)
				break;
			
			if(a[i]>a[i+1])
			{
				int temp = a[i];
				a[i] = a[i+1];
				a[i+1] = temp;
			}
		}
		int min = a[0];
		int max = a[1];
		for(int i=0;i<a.length;i=i+2)
		{
			if(a[i]<min)
			{
				min = a[i];
			}
		}
		
		for(int i=1;i<a.length;i=i+2)
		{
			if(a[i]>max)
			{
				max = a[i];
			}
		}
		
		if(a[a.length-1]>max)
		{
			max = a[a.length-1];
		}
		
		System.out.println(max);
		System.out.println(min);
	}
	
	
	//找出数组中最大的跟最小的
	public static void method2(int a[])
	{
		int min = a[0];
		int max = a[0];
		
		for(int i=0;i<a.length;i=i+2)
		{
			if(i==a.length-1)
				break;
			if(a[i]<a[i+1])
			{
				if(a[i]<min)
				{
					min = a[i];
				}
				if(a[i+1]>max)
				{
					max = a[i+1];
				}
			}
			else
			{
				if(a[i+1]<min)
				{
					min = a[i+1];
				}
				if(a[i]>max)
				{
					max = a[i];
				}
			}
		}
		
		if(a[a.length-1]>max)
		{
			max = a[a.length-1];
		}
		if(a[a.length-1]<min)
		{
			max = a[a.length-1];
		}
		System.out.println(min);
		System.out.println(max);
	}
	
	
	
	public static void findSecondMax(int a[])
	{
		if(a.length<=1)
		{
			System.out.println(" There is no secondMax");
			return ;
		}
		
		int max;
		int secondMax;
		
		max = a[0];
		secondMax = a[1];

		if(max<secondMax)
		{
			int temp = max;
			max = secondMax;
			secondMax = temp;
		}
		
		for(int i=2;i<a.length;i++)
		{
			if(a[i]>max)
			{
				secondMax = max;
				max = a[i];
			}
			else if(a[i]>secondMax)
			{
				secondMax = a[i];
			}
		}
		
		
		if(secondMax == max)
		{
			System.out.println("There is no second Max");
		}else
		{
			System.out.println(secondMax);
		}
	}
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics