6

how can i find the min value in int arry with c#

2 Answers 2

19

With LINQ:

int min = theArray.Min();

note that this will error if there aren't any elements; check the .Length first (or alternatively, project to int?, but that adds overhead).

If you don't have LINQ available, then perhaps:

public static int Min(int[] arr) {
    switch (arr.Length) {
        case 0: throw new InvalidOperationException();
        case 1: return arr[0];
        case 2: return Math.Min(arr[0], arr[1]);
        default:
            int min = arr[0];
            for (int i = 1; i < arr.Length; i++) {
                if (arr[i] < min) min = arr[i];
            }
            return min;
    }
}
Sign up to request clarification or add additional context in comments.

12 Comments

what does it mean? case 2: return Math.Min(arr[0], arr[1]); what are you doing in default?
Also what does it mean? case 1: return arr[0];?
@SaeedAlg - I'm checking the length of the array; if it case 1 item, then the min is obviously the first (only) item; if there are 2, then treat that as another special case because we can do so conveniently - otherwise we'll iterate over the array and find the minimum
You can do nothing with them, your default means you do this for array size of 1 or 2 there is no need to do this in case and you just need a simple if statement, but if you saying do it for readability it's acceptable.
@Doggett - fine, do it whichever way pleases you. Honestly,over-analyse much? The code as written will work fine and pass any (sane) test I can think of. Feel free to post the simpler version; I'll happily upvote it! But note also the first part of my answer... .Min()...
|
1

I wrote bellow to compare what i said by @Marc Gravell, the way I told is a little faster in my PC, and the linq one is slowest way, Also if you change the position of functions (in code) you will always gain a better performance with a version with if

    static void Main(string[] args)
    {
        Dictionary<string, List<long>> dic = new Dictionary<string, List<long>>();

        dic["First"] = new List<long>();
        dic["Second"] = new List<long>();
        dic["Third"] = new List<long>();


        for (int i = 0; i < 500; i++)
        {
            int[] array = GetRandomArray();
            Stopwatch stopWacth = new Stopwatch();
            stopWacth.Restart();
            int n1 = FindMin(array);
            stopWacth.Stop();
            long firstTicks = stopWacth.ElapsedTicks;
            dic["First"].Add(firstTicks);

            stopWacth.Restart();
            int n2 = AnotherFindMin(array);
            stopWacth.Stop();
            long secondTick = stopWacth.ElapsedTicks;
            dic["Second"].Add(secondTick);

            stopWacth.Restart();
            int n3 = array.Min();
            stopWacth.Stop();
            long thirdTick = stopWacth.ElapsedTicks;
            dic["Third"].Add(thirdTick);

            Console.WriteLine("first tick : {0}, second tick {1}, third tick {2} ", firstTicks, secondTick, thirdTick);
        }

        Console.WriteLine("first tick : {0}, second tick {1}, third tick {2} ", dic["First"].Average(), dic["Second"].Average(), dic["Third"].Average());

        Console.ReadLine();
    }


    public static int[] GetRandomArray()
    {
        int[] retVal = new int[1000000];
        Random r = new Random();
        for (int i = 0; i < 1000000; i++)
        {
            retVal[i] = r.Next(1000000000);
        }
        return retVal;
    }

    public static int FindMin(int[] arr)
    {
        switch (arr.Length)
        {
            case 0: throw new InvalidOperationException();
            case 1: return arr[0];
            case 2: return Math.Min(arr[0], arr[1]);
            default:
                int min = arr[0];
                for (int i = 1; i < arr.Length; i++)
                {
                    if (arr[i] < min) min = arr[i];
                }
                return min;
        }
    }

    public static int AnotherFindMin(int[] arr)
    {
        if (arr.Length > 0)
        {
            int min = arr[0];
            for (int i = 1; i < arr.Length; i++)
            {
                if (arr[i] < min) min = arr[i];
            }
            return min;
        }
        else
        {
            throw new InvalidOperationException();
        }
    }
}
// revised test by Marc (see comments discussion)
static class Test {
    static void Main(string[] args)
    {
        Dictionary<string, List<long>> dic = new Dictionary<string, List<long>>();

        dic["First"] = new List<long>();
        dic["Second"] = new List<long>();
        dic["Third"] = new List<long>();

        const int OUTER_LOOP = 500, INNER_LOOP = 500000;
        for (int arrSize = 1; arrSize <= 3; arrSize++)
        {
            for (int i = 0; i < OUTER_LOOP; i++)
            {
                int[] array = GetRandomArray(arrSize);
                Stopwatch stopWacth = Stopwatch.StartNew();
                for (int j = 0; j < INNER_LOOP; j++)
                {
                    int n1 = FindMin(array);
                }
                stopWacth.Stop();
                long firstTicks = stopWacth.ElapsedTicks;
                dic["First"].Add(firstTicks);

                stopWacth = Stopwatch.StartNew();
                for (int j = 0; j < INNER_LOOP; j++)
                {
                    int n2 = AnotherFindMin(array);
                }
                stopWacth.Stop();
                long secondTick = stopWacth.ElapsedTicks;
                dic["Second"].Add(secondTick);

                stopWacth = Stopwatch.StartNew();
                for (int j = 0; j < INNER_LOOP; j++)
                {
                    int n3 = array.Min();
                }
                stopWacth.Stop();
                long thirdTick = stopWacth.ElapsedTicks;
                dic["Third"].Add(thirdTick);

                //Console.WriteLine("{3}: switch : {0}, 0-check {1}, Enumerable.Min {2} ", firstTicks, secondTick, thirdTick, arrSize);
            }

            Console.WriteLine("{3}: switch : {0}, 0-check {1}, Enumerable.Min {2} ", dic["First"].Average(), dic["Second"].Average(), dic["Third"].Average(), arrSize);
        }
        Console.WriteLine("Done");
        Console.ReadLine();
    }


    public static int[] GetRandomArray(int size)
    {
        int[] retVal = new int[size];
        Random r = new Random();
        for (int i = 0; i < retVal.Length; i++)
        {
            retVal[i] = r.Next(1000000000);
        }
        return retVal;
    }

    public static int FindMin(int[] arr)
    {
        switch (arr.Length)
        {
            case 0: throw new InvalidOperationException();
            case 1: return arr[0];
            case 2: return arr[0] < arr[1] ? arr[0] : arr[1];
            default:
                int min = arr[0];
                for (int i = 1; i < arr.Length; i++)
                {
                    if (arr[i] < min) min = arr[i];
                }
                return min;
        }
    }

    public static int AnotherFindMin(int[] arr)
    {
        if (arr.Length > 0)
        {
            int min = arr[0];
            for (int i = 1; i < arr.Length; i++)
            {
                if (arr[i] < min) min = arr[i];
            }
            return min;
        }
        else
        {
            throw new InvalidOperationException();
        }
    }
}

12 Comments

A Stopwatch over a single iteration is not going to give a meaningful answer; also, this test only considers the default case (which to be fair is the most likely). And that array is so overwhelmingly large that any tests are barely showing any numbers from this choice of logic...
@Marc Gravell, I'd wroted it's average
(edit: my mistake, this is a 4.0 method) Also - Restart - is that an extension method of yours? I'm replacing (locally) with Stopwatch.StartNew()
@Marc Gravell, I think it's not meaningless, but if you think so whats your idea to compare them? I got the size of array to be big, so stopwatch shouldn't be meaningless, In all what's your suggestion?
No, I'm using using System.Diagnostics; in .Net 4, restart is not for me, @Marc Gravell, you should take care the assembly jumps, which is longer for my method
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.