Code to merge two array lists:
public static ArrayList<Integer> mergeLists(ArrayList<Integer> l1, ArrayList<Integer> l2){
ArrayList<Integer> l3 = new ArrayList<Integer>();
int i = 0;
int j = 0;
while(i < (l1.size()) && j < (l2.size())){
if(l1.get(i) < l2.get(j)){
l3.add(l1.get(i));
i++;
}else {
l3.add(l2.get(j));
j++;
}
}
if(i < l1.size()){
while(i < l1.size()){
l3.add(l1.get(i));
i++;
}
}else if(j < l2.size()){
while(j < l2.size()){
l3.add(l2.get(j));
j++;
}
}
return l3;
}
Code to merge two arrays:
public static int[] mergeArrays(int[] a, int[] b){
if((a == null || a.length == 0) && (b == null || b.length == 0))
return new int[0];
if((a == null || a.length == 0))
return b;
if(b == null || b.length == 0)
return a;
int[] c = new int[a.length + b.length];
int i,j,k;
i = j = k = 0;
while(i < a.length && j < b.length){
if(a[i] <= b[j]){
c[k++] = a[i++];
}else
{
c[k++] = b[j++];
}
}
while(i < a.length){
c[k++] = a[i++];
}
while(j < b.length){
c[k++] = b[j++];
}
return c;
}
Complexity:
If length of the first array a and length of the second array is b, then complexity of this algorithm is O(a+b).
if((a == null || a.length == 0) && (b == null || b.length == 0))
return new int[0];
if((a == null || a.length == 0))
return b;
if(b == null || b.length == 0)
return a;
int[] c = new int[a.length + b.length];
int i,j,k;
i = j = k = 0;
while(i < a.length && j < b.length){
if(a[i] <= b[j]){
c[k++] = a[i++];
}else
{
c[k++] = b[j++];
}
}
while(i < a.length){
c[k++] = a[i++];
}
while(j < b.length){
c[k++] = b[j++];
}
return c;
}
Complexity:
If length of the first array a and length of the second array is b, then complexity of this algorithm is O(a+b).
Comments
Post a Comment