首页 > 技术文章 > 求给定数组中最大值和其在数组中的索引并输出

dfyg-xiaoxiao 2014-02-11 21:49 原文

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


namespace _03
{
    class Program
    {
        static void Main(string[] args)
        {
            //求给定数组中最大值和其在数组中的索引并输出
            int[] intArray = { 1, 4, 34, 23, 45, 45, 23, 78, 12, 78 };  //int数组
            List<int> index = new List<int>();//声明集合 用于存放最大值的索引
            int max = 0;//存最大值
            max = CheckMax(intArray, out  index);//调用方法查找最大值和其索引
             Console.Write("最大值是:{0},其在数组中的索引是", max);
            foreach (int item in index)//遍历最大值所在数组的索引
            {
                Console.Write("{0}\t", item);
            }
            Console.ReadKey();
        }
        /// <summary>
        /// 找出给定int数组中最大值和最大值的索引
        /// </summary>
        /// <param name="intArray">数组</param>
        /// <param name="index">存最大值在数组中的索引</param>
        /// <returns>最大值  最大值的索引</returns>
        private static int CheckMax(int[] intArray, out List<int> index)
        {
            index = new List<int>();//为index赋初值,   注:用out修饰的参数在使用前必须对其赋值
            int max = 0;
            for (int i = 0; i < intArray.Length; i++)
            {
                if (max < intArray[i])//如果有大于当前所得最大值,清空list,并将该值赋给max
                {
                    index.Clear();
                    max = intArray[i];
                    index.Add(i);
                }
                else if (max == intArray[i])//重复最大值时,向list中添加其索引
                {
                    index.Add(i);
                }
            }
            return max;
        }
    }
}

推荐阅读