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;
}
}
}