Im stuck on this question can you explain it to me step by s

I\'m stuck on this question. can you explain it to me step by step. thanks!

Let S = S[0], S[1]...., S[n - 1] be a sequence of n distinct elements 011 which a total order relation is defined. We say that two elements and S[i] and S[j] in S are a friendly pair if S[i]

Solution

Solution--

I have defined two functions here count_pairs(S) and count_and_sort(S1,S2) . count_pairs(S) recursively calls itself on dividing the array into two halves and then the calls count_and_sort(S1,S2) to combine them in a manner such that the combined array is sorted and in the process count the number of friendly_pairs.

It is just like merge sort , the additional part is that it counts the friendly pairs while combining.

count_and_sort(S1,S2):

S1 and S2 are two sorted lists.

Let S3 be the output list after sorting and merging

Let i,j be the pointers to the beginning to the lists S1,S2

Let s1[i] and s2[j] be the elements pointed to by i and j

Let count be #(friendly_pairs)

while(i<=length(S1) and j<=length(S2)):

if(s2[j]>s1[i]):

count++

append s1[i] to S3 and i++

else:

append s2[j] to S3 and j++ # no increment in count because of s2[j] because it will be less than all elements ahead of s1[i] because the lists are sorted.

now we are out of the loop when one of the lists is empty and we append remaining elements of other list to S3

return S3,count

count_pairs(S):

if(len(S)<=1):

return 0 # no pairs can exist

else:

divide S into S1,S2

S1,c1=count_pairs(S1)

S2,c2=count_pairs(S2)

S,c3=count_and_sort(S1,S2)

final_count=c1+c2+c3

return S,final_count

I\'m stuck on this question. can you explain it to me step by step. thanks! Let S = S[0], S[1]...., S[n - 1] be a sequence of n distinct elements 011 which a to

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site