5. Define a Scheme function, (merge 11 12), which takes two lists e1 and l2 as a
ID: 3598016 • Letter: 5
Question
5. Define a Scheme function, (merge 11 12), which takes two lists e1 and l2 as arguments. As- suming that each of l1 and l2 are sorted lists of integers (in increasing order, say), merge must return the sorted list containing all elements of l1 and l2 To carry out the merge, observe that since l and l2 are already sorted, it is easy to find the smallest element among all those in E and (2: it is simply the smaller of the first elements of (1 and l2. Removing this smallest element from whichever of the two lists it came from, we can recurse on the resulting two lists (which are still sorted), and place this smallest element at the beginning of the result.Explanation / Answer
Since this question doesnot specific to any laugage. I am writing my code in java with comments.
public static int[] merge(int[] l1, int[] l2)
{
int i = 0, j = 0, k = 0;
int len1 = l1.length;
int len2 = l2.length;
int[] l3 = new int[len1+len2];
// Traverse both array
while (i<len1 && j <len2)
{
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (l1[i] < l2[j])
l3[k++] = l1[i++];
else
l3[k++] = l2[j++];
}
// Store remaining elements of first array
while (i < len1)
l3[k++] = l1[i++];
// Store remaining elements of second array
while (j < len2)
l3[k++] = l2[j++];
System.out.println("Array after merging");
for ( i=0; i < len1+len2; i++)
System.out.print(l3[i] + " ");
return l3;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.