Write a program to find an index of Max item in an array

  • A+
Category:Languages

Write a console app in C# to find an index i in an array that is the maximum number in the array.

If the maximum element in the array occurs several times, you need to display the minimum index.

If the array is empty, output -1.

Please let me know what is wrong in my code. If I input the array a = { 1, 2, 46, 14, 64, 64 };, for instance, it returns 0, while it should be returning 4.

  public static void Main()   {      double[] a = { 1, 9, 9, 8, 9, 2, 2 };      Console.WriteLine(MaxIndex(a));   }    public static double MaxIndex(double[] array)   {      var max = double.MinValue;      int maxInd = 0, maxCount = 0;      int minIndex = 0;      var min = double.MaxValue;      for (var i = 0; i < array.Length; i++)      {         if (min > array[i])         {            min = array[i];            minIndex = i;          }         if (max == array[i])            maxCount++;         if (max < array[i])         {            maxCount = 1;            max = array[i];            maxInd = i;         }      }       if (array.Length == 0)         return -1;      if (maxCount > 1)         return minIndex;      return maxInd;   } 

 


Your calculation is correct, but you return the wrong variable minIndex instead of maxIndex. Don't do more than necessary in a method. This calculates also the min-index and the count how often it appears, then it does nothing with the results. Here is a compact version:

public static int MaxIndex(double[] array) {     if(array.Length == 0)          return -1;      var max = double.MinValue;     int maxInd = -1;      for (int i = 0; i < array.Length; i++)     {         if (max < array[i])         {             max = array[i];             maxInd = i;         }     }      return maxInd; } 

It also sets maxInd = -1 which was part of your requirement. Since MatthewWatson had an objection regarding repeating double.MinValue in the array, here is an optimized version:

public static int MaxIndex(double[] array) {     if(array.Length == 0)         return -1;     else if (array.Length == 1)         return 0;      double max = array[0];     int maxInd = 0;      for (int i = 1; i < array.Length; i++)     {         if (max < array[i])         {             max = array[i];             maxInd = i;         }     }      return maxInd; } 

If code-readability/maintainability is more important and you don't care of few milliseconds more or less, you could use LINQ (a version that enumerates only once):

int minIndexOfMaxVal = a.Select((num, index) => new {num, index})     .OrderByDescending(x => x.num)     .Select(x => x.index)     .DefaultIfEmpty(-1)     .First(); 

This works with every kind of sequence and types not only with arrays and doubles.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: