Skip to content

Instantly share code, notes, and snippets.

@Staticity
Last active October 8, 2015 19:31
Show Gist options
  • Save Staticity/8d9afb0f1fd71acfccf8 to your computer and use it in GitHub Desktop.
Save Staticity/8d9afb0f1fd71acfccf8 to your computer and use it in GitHub Desktop.
Merge two sorted generic lists.
import java.util.List;
import java.util.ArrayList;
public class Merge
{
public static void main(String args[])
{
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
a.add(1);
a.add(3);
b.add(2);
b.add(4);
System.out.println(merge(a, b));
}
public static <E extends Comparable<E>> List<E> merge(List<E> a, List<E> b)
{
List<E> m = new ArrayList<E>();
int i1 = 0, i2 = 0;
while (i1 < a.size() && i2 < b.size())
{
if (a.get(i1).compareTo(b.get(i2)) <= 0)
{
m.add(a.get(i1++));
}
else
{
m.add(b.get(i2++));
}
}
while (i1 < a.size())
{
m.add(a.get(i1++));
}
while (i2 < b.size())
{
m.add(b.get(i2++));
}
return m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment