Merging two sorted arrays with second array having trailing space to accommodate first array

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] A = { 1, 4, 5, 6, 7 };//m = 5
            int[] B = new int[8];//n = 3 and having m+n space
            int n = 3;
            B[0] = 5;
            B[1] = 8;
            B[2] = 9;
            for (int i = B.Length - 1, j = A.Length - 1, k = n - 1; i >= 0; i--)
            {
                if (j >= 0 && k >= 0)
                {
                    if (A[j] >= B[k])
                    {
                        B[i] = A[j];
                        j--;
                    }
                    else
                    {
                        B[i] = B[k];
                        k--;
                    }
                }
                else if (k < 0)
                {
                    B[i] = A[j];
                    j--;
                }
                else
                {
                    B[i] = B[k];
                    k--;
                }
            }
            for (int i = 0; i < B.Length; i++)
            {
                Console.Write(B[i] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output
=======
1 4 5 5 6 7 8 9
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s