-
Notifications
You must be signed in to change notification settings - Fork 145
/
Q10_01_Sorted_Merge.cs
47 lines (44 loc) · 1.63 KB
/
Q10_01_Sorted_Merge.cs
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using ctci.Contracts;
using ctci.Library;
using System;
namespace Chapter10
{
public class Q10_01_Sorted_Merge : Question
{
/// <summary>
/// Merges array
/// </summary>
/// <param name="a">first array</param>
/// <param name="b">second array</param>
/// <param name="lastA">number of "real" elements in a</param>
/// <param name="lastB">number of "real" elements in b</param>
private void Merge(int[] a, int[] b, int lastA, int lastB)
{
int indexMerged = lastB + lastA - 1; /* Index of last location of merged array */
int indexA = lastA - 1; /* Index of last element in array b */
int indexB = lastB - 1; /* Index of last element in array a */
/* Merge a and b, starting from the last element in each */
while (indexB >= 0)
{
if (indexA >= 0 && a[indexA] > b[indexB])
{ /* end of a is bigger than end of b */
a[indexMerged] = a[indexA]; // copy element
indexA--;
}
else
{
a[indexMerged] = b[indexB]; // copy element
indexB--;
}
indexMerged--; // move indices
}
}
public override void Run()
{
int[] a = new int[] { 2, 3, 4, 5, 6, 8, 10, 100, 0, 0, 0, 0, 0, 0 };
int[] b = new int[] { 1, 4, 7, 6, 7, 7 };
Merge(a, b, 8, 6);
Console.WriteLine(AssortedMethods.ArrayToString(a));
}
}
}