Tuesday 5 January 2016

Best practice code

All questions list

Problem 1: sort the given array
                    Input--> [-8, -5, -3, -1, 3, 6, 9
                    Output-->[1,3,3,5,6,8,9]
Solution:
Private int[] SortedArray()
{
        int[] a = { -8, -5, -3, -1, 3, 6, 9 };
            for (int i = 0; i < a.Length; i++)
            {
             
                for (int j = i; j < a.Length; j++)
                {
                    int x = Convert.ToInt32(a[i]);
                    if (x < 0)
                    {
                        x = x * (-1);
                    }
                    int y = Convert.ToInt32(a[j]);
                    if (y < 0)
                    {
                        y = y * -1;
                    }
                    if (x > y)
                    {
                        int temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                        x=a[i];
                    }
                }
            }
            return a;
}
----------------------------------------------------------------------------------------------------------------------

2. Given an array A of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of A.

static void Main(string[] args)
        {
            Program p = new Program();
            int[] arr = { 11, -12, 15, -3, 8, -9, 1, 8, 10, -2 };
            int answer = p.maxSum(arr, 10);//answer should be 30
        }
        int maxSum(int[] a, int n)
        {
            int i, j, k;
            int sum, maxSum = 0;
            for (i = 0; i < n; i++)
            {
                for (j = i; j < n; j++)
                {
                    sum = 0;
                    for (k = i; k < j; k++)
                    {
                        sum = sum + a[k];
                    }
                    if (sum > maxSum)
                        maxSum = sum;
                }
            }
            return maxSum;

        }

 OR

static void Main(string[] args)
        {
            Program p = new Program();
            int[] arr = { 11, -12, 15, -3, 8, -9, 1, 8, 10, -2 };
            int answer = p.maxSum(arr, 10);
        }
        int maxSum(int[] a, int n)
        {
            int i, j, sum, maxSum;
            maxSum = 0;
            for (i = 0; i < n; i++)
            {
                sum = 0;
                for (j = i; j < n; j++)
                {
                    sum = sum + a[j];
                    if (sum > maxSum)
                        maxSum = sum;
                }
            }
            return maxSum;

        }
-----------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft