//Given two sorted integer arrays A and B, merge B into A as one sorted array.
//example 1346789
// 35689
var arr1 = new List<int> { 4,5 };
var arr2 = new List<int> { 1,2,3 };
//Loop length of arr1 - start 0 untill end of array - p = index
//Optimization use shortest array
//Pick element at p, compare it with all elements in arr2 - Loop Arr2 start from last point examined
//if arr1 Element <= arr2 element and < arr2
//insert arr1 element left of arr2 element, otherwise keep going
var r2 = arr2.Count;
for (int p = 0; p < arr1.Count; p++)
{
for (int j = 0; j < r2; j++)
{
if (arr1[p] <= arr2[j])
{
arr2.Insert(j, arr1[p]);
r2 = arr2.Count;
break;
}
if (j == r2-1) //Last item in arr2 and loop did not break above
{
arr2.Add(arr1[1]);
r2 = arr2.Count;
}
}
}
No comments:
Post a Comment