数据结构-合并两个已经排序的数组

合并两个已经排序的数组

 1 /// <summary>
 2         /// 合并两个已经排序的数组
 3         /// </summary>
 4         /// <param name="arr1"></param>
 5         /// <param name="arr2"></param>
 6         public static void MergeSortedArray(int[] arr1,int[] arr2)
 7         {
 8             List<int> list = new List<int>();
 9             int i = 0;
10             int j = 0;
11             do
12             {
13                 if (arr1[i] < arr2[j])
14                 {
15                     list.Add(arr1[i]);
16                     i++;
17                 }
18                 else if (arr1[i] == arr2[j])
19                 {
20                     list.Add(arr1[i]);
21                     list.Add(arr2[j]);
22                     i++;
23                     j++;
24                 }
25                 else if (arr1[i] > arr2[j])
26                 {
27                     list.Add(arr2[j]);
28                     j++;
29                 }
30             }
31             while (i < arr1.Length && j < arr2.Length);
32             //如果有的数组还没有添加结束,就将剩下的元素都添加到新集合中;
33             if(i<arr1.Length)
34             {
35                 for(;i<arr1.Length;i++)
36                 {
37                     list.Add(arr1[i]);
38                 }
39             }
40             else if (j < arr2.Length)
41             {
42                 for (; j < arr2.Length; j++)
43                 {
44                     list.Add(arr2[j]);
45                 }
46             }
47 
48             foreach(var item in list)
49             {
50                 Console.WriteLine(item+",");
51             }
52             Console.ReadKey();
53         }
原文地址:https://www.cnblogs.com/luoshengjie/p/10366220.html