求数组中的最大数,最小数。

方法是把数组中的数按2个2个的分成一组,先对比他们俩,然后再对比MAX和MIN。最后再加个判断,如果是奇数,那最后一个数字也要和MAX和MIN判断。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] input = { 1,2,-1,3,55,1};
            int max = 0;
            int min = 0;
            FindMaxAndMin(input, ref max, ref min);
        }

        static void FindMaxAndMin(int[] input, ref int max, ref int min)
        {
            if (input==null||input.Length == 0)
            {
                throw new Exception("input array can't be empty");
            }
            if (input.Length==1)
            {
                throw new Exception("only on element in array, no max and min number");
            }
            max = input[0];
            min = input[0];
            int i = 0;

            for (; i +1 < input.Length; i= i+2)
            {
                if (input[i]>input[i+1])
                {
                    if (input[i]>max)
                    {
                        max = input[i];
                    }
                    if (input[i+1]<min)
                    {
                        min = input[i + 1];
                    }
                }
                else
                {
                    if (input[i]<min)
                    {
                        min = input[i];
                    }
                    if (input[i+1]>max)
                    {
                        max = input[i + 1];
                    }
                }
            }

            if (i<input.Length)
            {
                if (input[i]>max)
                {
                    max = input[i];
                }
                if (input[i]<min)
                {
                    min = input[i];
                }
            }

            Console.WriteLine("Max item is {0}, Min item is {1}",max,min);

        }
    }
}
View Code
原文地址:https://www.cnblogs.com/Ligeance/p/3537762.html