Interview Question Categories

[a1,a2,a3,b1,b2,b3] to [a1,b1,a2,b2,a3,b3] in Place

[a1,a2,a3,b1,b2,b3] to [a1,b1,a2,b2,a3,b3] in Place


namespace ArrayProblem
{
    //Suppose an array is of the form [i1,i2,i3,i4,c1,c2,c3,c4] where i[1..n] is 
   //a set of integer elements and c[1..n] is another set of integer elements. 
    //Write an in place algorithm so that the resulting array is of the form 
//[i1,c1,i2,c2,i3,c3,i4,c4]. State optimized time and space complexities.
    //Example: array: [1,7,9,4,11,12,13,14] should become [1,11,2,12,3,13,4,14].
    class Program
    {
        public static void ModifyArray(int[] Arr)
        {
            int n = Arr.Length / 2;
            int temp;

            for (int i = n - 1; i > 0; i--)
            {
                for (int j = n - 1; i + j >= n; j--)
                {
                    temp = Arr[j];
                    Arr[j] = Arr[i + j];
                    Arr[i + j] = temp;
                }
                //Print the array to see the modification process
                foreach (int x in Arr)
                {
                    Console.Write(x + " ");
                }
                Console.WriteLine();
            }
        }

        static void Main(string[] args)
        {
            int[] Arr = { 1, 2, 3, 4, 11, 12, 13, 14 };

            ModifyArray(Arr);

            foreach (int x in Arr)
                Console.WriteLine(x);

        }
    }
}

No comments:

Post a Comment