张德长

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

合并两个有序数组的算法

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

//合并两个有序数组-升序
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   张德长  阅读(85)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示