October 10, 2014

One Algorithm per day (C#): Merge two sorted Arrays and keep duplicate values


int[] Arr= {1, 5, 6, 8, 10, 15, 20, 23, 27, 29, 30, 32};
int[] Arr2 = {5};

int i = 0;
int j = 0;
int k = 0;
int m = Arr.Count() + Arr2.Count();
int[] Arr3 = new int[m];

while(k < m){
if(i < Arr.Count() && j < Arr2.Count()){
 if(Arr[i] < Arr2[j]){
  Arr3[k] = Arr[i];
  i++;
 }else if(Arr[i] < Arr2[j]){
  Arr3[k] = Arr2[j];
  j++;
 }else{
  Arr3[k] = Arr2[j];
  Arr3[k+1] = Arr[i];
  i++;
  j++;
  k++;
 }
}else if(i < Arr.Count()){
 Arr3[k] = Arr[i];
 i++;
}else{
 Arr3[k] = Arr2[j];
 j++;
}
k++;
}

foreach (int num in Arr3)
 Console.WriteLine(num);

No comments: