Saturday, December 29, 2007

C#: Find max in an array

public int getMax(int[] thearray)
{
int max = 0;
for (int i = 1; i != thearray[max]; )
{
max = i;
}
return thearray[max];
}

12 comments:

  1. Errrrh, the code above isn't even valid C#.

    Change the "<>" operator to "!=" and add a ";" at the end of the for loop construct. Then you have valid C# code.
    However, the snippet will always return 1 or go into infinite loop.

    ReplyDelete
  2. LarsL,
    Thanks for the catch. I am sorry about the typo, and I have corrected the code.

    Anonymous,
    I do not think that comment you made was appropriate (yes that's my discretion). Please refrain yourself from making such comments in the future. I ONLY welcome constructive critism on my blog.

    ReplyDelete
  3. public void getMaxIndex(int[] thearray)
    {
    int k =0;
    foreach (int j in thearray)
    {

    if (j > k)
    k = j;

    }
    Console.WriteLine("The max number in array is:{0}",k);

    }

    ReplyDelete
  4. It still isn't corrected, because first of all there is no update to the loop counter, secondly array indices start at 0 rather than 1, thirdly the assignment to 'max' is currently unconditional, and finally you are using a completely nonsensical condition for the loop limit (using the current 'max' position to index into the array and using the value there to grab an index).

    Nor Sivad has nearly correct code: it has a bug in that if the array contains all negative numbers, the result will be 0, which is incorrect. This code uses the modern looping idiom, too. However, it does make more sense to return the value rather than display it, and fixing the bug neatly requires a more careful iteration strategy.

    You want something like this instead:

    public int getMax(int[] thearray)
    {
    // Throws NullReferenceException if thearray is null
    // Throws IndexOutOfRangeException if thearray is zero length
    int max = thearray[0];
    for (int i = 1; i != thearray.Length; ++i)
    {
    if (thearray[i] > max) { max = thearray[i]; }
    }
    return max;
    }

    ReplyDelete
  5. This is some serious dailyWTF material!

    ReplyDelete
  6. Better is something like that. (.NET 3.5)

    public int getMax(int[] arr)
    {
    return arr.Max();
    }

    ReplyDelete
  7. Dirk: finally nice and elegant solution instead inventing a wheel again, thx

    ReplyDelete
  8. nice post

    http://csharptalk.com

    ReplyDelete
  9. The better solution is the Dirk's one.
    But in 2.0 I use:

    public int getMax(int[] arr)
    {
    int max = 0;
    foreach(int val in arr)
    max = Math.Max(max, val);
    return max;
    }

    ReplyDelete
  10. 2 anonimo viaggiatore
    what if 'arr' contains negatives only? =)

    ReplyDelete
  11. Hi Try this,

    public static double getMax(double[] valArray)
    {
    double? max = null;
    foreach (double val in valArray)
    {
    string minus = string.Empty;
    double actualVal = val;
    if (val.ToString().IndexOf("-") != -1)
    {
    minus = "-";
    actualVal = Convert.ToDouble(val.ToString().Replace("-", ""));
    }
    max = Math.Max(max.GetValueOrDefault(), actualVal);
    max = Convert.ToDouble(minus + max.Value.ToString());
    }
    return max.GetValueOrDefault();
    }

    The above code will provide the max value from an array does not matter about negative or positive.

    ReplyDelete
  12. Hi,
    Ignore my previous post and try this.
    The below code will provide the max value from an array does not matter about negative or positive.

    public static double getMax(double[] valArray)
    {
    double? max = valArray[0];
    foreach (double val in valArray)
    {
    max = Math.Max(max.GetValueOrDefault(), val);
    }
    return max.GetValueOrDefault();
    }

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.