# 数据结构：将两个有序的数组合并成一个有序数组

static void Main(string[] args)
{
int[] arr = new int[] { 14,12,15,13,11,16 ,10};

int[] newArr = Sort(arr, new int[7], 0, arr.Length - 1);
for (int i = 0; i < newArr.Length - 1; i++)
{
Console.WriteLine(newArr[i]);
}

}

public static int[] Sort(int[] arr, int[] result, int start, int end)
{
if (start >= end)
return null;
int len = end - start, mid = (len >> 1) + start;
int start1 = start, end1 = mid;
int start2 = mid + 1, end2 = end;
Sort(arr, result, start1, end1);
Sort(arr, result, start2, end2);
int k = start;
//进行比较。注意这里++是后执行的，先取出来数组中的值然后++
while (start1 <= end1 && start2 <= end2)
result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++];
//将每个分组剩余的进行复制
while (start1 <= end1)
result[k++] = arr[start1++];
//将每个分组剩余的进行复制
while (start2 <= end2)
result[k++] = arr[start2++];
for (k = start; k <= end; k++)
arr[k] = result[k];
return result;
}

static void Main(string[] args)
{
int[] arr1 = new int[] { 2, 3, 6, 8 };
int[] arr2 = new int[] { 1, 4, 5, 7 };
int[] newArr = Sort(arr1, arr2);
for (int i = 0; i < newArr.Length - 1; i++)
{
Console.WriteLine(newArr[i]);
}

}

public static int[] Sort(int[] arr1,int[] arr2)
{
int[] newArr = new int[arr1.Length + arr2.Length];
int i = 0, j = 0, k = 0;
while (i < arr1.Length && j < arr2.Length)
{
if (arr1[i] < arr2[j])
{

newArr[k] = arr1[i];
i++;
k++;
}
else
{

newArr[k] = arr2[j];
j++;
k++;
}
}

while (i < arr1.Length)
newArr[k++] = arr1[i++];
while (j < arr2.Length)
newArr[j++] = arr2[j++];
return newArr;
}
}

• 6
点赞
• 12
收藏
• 打赏
• 0
评论
07-06 5656
12-01 616
03-02 3460
11-03 286
06-13 2万+
12-11 7978
09-08 260
05-20 3万+
07-20 4816
05-26 366

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。