Question

Write a function

intersect(L, M)

that consumes two sorted lists of distinct integers L and M, and returns a sorted list that contains only elements common to both lists.

You must obey the following restrictions:

- No recursion or abstract list functions,
- intersect must run in O(n) where n is the combined length of the two parameters.

**Example:**

intersect([3, 7, 9, 12, 14], [1, 2, 5, 7, 10, 11, 12]) => [7, 12]

**Hint:** As the title hints at, you are mostly
doing the same thing as the merge function from merge sort.
Mostly.

**DO NOT USE** dictionaries, commands continue or
break, zip, anything with set or enumerator, etc.).

Do **not** mutate passed parameters unless
otherwise told to.

Answer #1

**note:**

The programming language is not specified.

It is mentioned thet use of dictionaries is not allowed. So I recognize the language as python.

If you need the code in other programming language please comment.

**Code in
python:**

```
//Function that returns an sorted intersected list
def intersect(L, M):
i,j = 0,0
m=len(L)
n=len(M)
Intersect=[]
while i < m and j < n:
if L[i] < M[j]:
i += 1
elif M[j] < L[i]:
j+= 1
else:
Intersect.append(M[j])
j += 1
i += 1
return Intersect
```

**Example output of
above example in python shell:**

In Python, implement a function that takes in two sorted lists
and merges them into one list, the new list must be sorted. The
function MUST run in O(m+n), where m is the length of list 1 and n
the length of list 2. In other words, the function cannot do more
than one pass on list 1 and list 2.

convert code from python to cpp
L =
[2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]
#Merging function
def merge(M,N):
merging_list = [] //create empty
list to merge the lists M and N
if not M:
//if M is empty list,
m = 0
//set m = 0
else:
m = len(M)
//otherwise, set m = len(M)
if not N:
//if N is empty list,
n = 0 ...

ADVERTISEMENT

Get Answers For Free

Most questions answered within 1 hours.

ADVERTISEMENT

asked 15 minutes ago

asked 45 minutes ago

asked 51 minutes ago

asked 59 minutes ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago