张德长

导航

合并两个有序数组的算法

两个数组都是升序或者降序

//合并两个有序数组-升序
        static int[] CombineArray(int[] a, int[] b)
        {
            int index = 0, indexa = 0, indexb = 0;
            int count = a.Length + b.Length;
            int[] result = new int[count];

            while (index < count)
            {
                //a已经遍历完,而b还没有遍历完,把b剩余部分逐个复制到result
                if (indexa == a.Length && indexb < b.Length)
                {
                    result[index] = b[indexb];
                    indexb++; index++;
                    continue;//不再执行下面的代码
                }
                //b已经遍历完,而a还没有遍历完,把a剩余部分逐个复制到result
                if (indexb == b.Length && indexa < a.Length)
                {
                    result[index] = a[indexa];
                    indexa++; index++;
                    continue;//不再执行下面的代码
                }
                //都没有遍历完的情形

                if (a[indexa] < b[indexb])
                {
                    result[index] = a[indexa];
                    indexa++;
                }
                else
                {
                    result[index] = b[indexb];
                    indexb++;
                }
                index++;
            }
            return result;
        }

测试

        static void test9()
        {
            int count1 = 100,count2=120;
            Random r = new Random();
            int[] a = new int[count1];
            int[] b = new int[count2];
            for (int i = 0; i < count1; i++)
            {
                a[i] =i*10+ r.Next(0, 10);
            }
            for (int i = 0; i < count2; i++)
            {
                b[i] = i * 10 + r.Next(0, 10);
            }
            int[] result = CombineArray(a, b);
            showArray(a);
            showArray(b);
            showArray(result);
        }
        //输出数组
        static void showArray(int[] result)
        {
            for (int i = 0; i < result.Length; i++)
            {
                Console.Write(result[i] + ",");
            }
            Console.WriteLine();
        }

运行结果

posted on 2022-06-04 18:07  张德长  阅读(66)  评论(0编辑  收藏  举报