合并两个有序数组

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 11, 12, 66, 99 };
            int[] b = { 7, 8, 13, 44 };

            List<int> alist = new List<int>();
            List<int> blist = new List<int>();
            for (int i = 1; i <= 100 * 10000; i++)
            {
                alist.Add(i);
            }
            for (int i = 1000001; i <= 200 * 10000; i++)
            {
                blist.Add(i);
            }
            //a = alist.ToArray();
            //b = blist.ToArray();
            int[] c = MergeArr(a, b);
            for (int i = 0; i < c.Length; i++)
            {
                Console.WriteLine(c[i]);

            }
            Console.Read();
        }

        private static T[] MergeArr<T>(T[] a, T[] b) where T : IComparable
        {
            List<T> arr = new List<T>();
            int maxIndex = a.Length - 1;
            bool ia = false;
            bool ib = false;
            int aindex = 0;
            int bindex = 0;
            while (true)
            {

                if (aindex > maxIndex)
                {
                    ia = true;
                    break;
                }
                if (bindex > maxIndex)
                {
                    ib = true;
                    break;
                }

                if (a[aindex].CompareTo(b[bindex]) <= 0)
                {
                    arr.Add(a[aindex]);
                    aindex++;
                }
                else
                {
                    arr.Add(b[bindex]);
                    bindex++;

                }
            }

            if (ia)
            {
                for (int index = bindex; index <= maxIndex; index++)
                {
                    arr.Add(b[index]);
                }
            }
            if (ib)
            {
                for (int index = aindex; index <= maxIndex; index++)
                {
                    arr.Add(a[index]);
                }
            }
            return arr.ToArray();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/kexb/p/9261245.html