Skip to content

Instantly share code, notes, and snippets.

@djvita
Created April 26, 2014 16:51
Show Gist options
  • Save djvita/11324972 to your computer and use it in GitHub Desktop.
Save djvita/11324972 to your computer and use it in GitHub Desktop.
Given two sorted arrays of integers, write a method to merge the two sorted arrays of integers into a single sorted array of integers. For example: Given the arrays [1,3,5] and [2,4], your method would return [1,2,3,4,5].
using System;
using System.Collections.Generic;
using System.Text;
namespace Excercise1{
public Class Program {
public static void Main(string[] args)
{
int[] a = {1, 3, 5};
int[] b = {2,4};
int[] resp = merge(a,b);
Console.Writeline("The arrays are {0}\n {1}\n And merged:\t {2}\n", a, b, resp);
Console.Read();
}
//method to merge two sorted arrays of ints into one.
public static int[] merge(int a[], int b[]){
int i=0, int j = 0, int k =0;
int result = new int[a.length + b.length];
//assuming that really a.length<b.length
//while the lengths of the arrays are smaller than i and k,
//and there is a difference between the parameter arays, input to a, else b
while(i < a.length && j < b.length)
{
if(a[i]< b[i])
{
result[k++]=a[i++];
}
else
{
result[k++]=b[i++] ;
}
//now to check if array a is smaller, still add to the result
while(i < a.length)
{
result[k++]=a[i++];
}
while(j < b.length)
{
result[k++]=b[i++];
return result;
}
}
//verifying in visual studio...ok!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment