Tuesday, August 23, 2011

C# code to find the min value in an array

Question:  Write a method to find the min value in an array.

What an Interviewer is looking far?
Think about the test cases clearly
Example:
Your input array can be in any of the following format 
           int[] intArray = null;
            int[] intArray = {};
            int[] intArray = { 1, 2, 3, 4, 5 };
            int[] intArray = { 1, 3, 5, 7, 9 };
            int[] intArray = { -1, -2, -3, -4, -5 }; 
            int[] intArray = { -5, -2, 0, -4, 5 }; 
            int[] intArray = { -1, -5, -3, -4, -2 }; 

I can think about 20 different test case for this input array.

Possible Solutions:
1. Use Hashtable
2  Take a[0] as pivot and using a for-loop traverse the array and find the min element
3. Use sorting algorithm- Eg bubble sort.

a[0] as pivot element and find a min value of an array
 private static void getMinValue(int[] intArray) //throws Exception
        {
            if (intArray != null)
            {
                //throw new System.ArgumentNullException();// Exception("\n Invalid intArray as it is null");
                Console.ReadLine();
            }
            else
            {
                throw new Exception("exception for null");
                Console.WriteLine("I am in Null check else block");
            }
            if (intArray.Length == 0)
            {
                Console.WriteLine("There are no elements in the array");
                Console.ReadLine();
            }
            else
            {
                int min = intArray[0];
                for (int i = 0; i < intArray.Length; i++)
                {
                    if (intArray[i] < min)
                    {
                        min = intArray[i];
                    }
                }
                Console.WriteLine("Min value in the array : " + min);               
            }
        }
 

No comments:

Post a Comment