求一个数组中所有元素的最大值及其索引位置

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

namespace FindMaxWithIndex
{
    /// <summary>
    /// 有一个数组,每个元素的值都是实数,请写出求最大元素的值及其位置的算法
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            double[] Num = new[] { -8, 4543.9, 4543.9, 3, 45, 654.7, 7, 66, 35, 45, 4, 6, 4543.9, 5, 46, 54, 6, 43, 5.980, 34, 4543.9 };
            //double[] Num = new [] { 1.0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };


            int[] index = SearchMaxWithIndex(Num);

            Console.WriteLine("The max number is: {0}", Num[index[0]]);
            Console.Write("The index of max number is:");

            for (int i = 0; i < index.Length; i++)
            {
                if (index[i] == -1) break;
                Console.Write(" '{0}'", index[i]);
            }

            Console.ReadKey();
        }

        private static int[] SearchMaxWithIndex(double[] arr)
        {
            int[] pos = new int[arr.Length];  //记录最大值所在位置的数组

            int position = 0; //初始设定数组的第1个元素为最大值

            int j = 1;//j指示位置数组pos的下标

            for (int i = 1; i < arr.Length; i++)
            {
                if (arr[i] > arr[position])
                {
                    position = i; //记下新的最大值的位置
                    j = 1; //位置数组pos的下标恢复为1,下标为0的位置为position预留
                }
                else if (arr[i] == arr[position])
                    pos[j++] = i; //记下重复最大值的位置
            }

            pos[0] = position;  //位置数组pos的下标为0的位置为position预留

            if (j < arr.Length) pos[j] = -1; //-1为标识值,表示位置数组pos下标为0, 1, 2…(j-1)的位置存放的是最大值所在的位置

            return pos;
        }
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值