Let A = {a1, . . . , ak} and B = {b1,. . . , bm} be two sets of numbers. Consider the problem of finding the difference set of A and B(A–B), i.e., the set of all elements of A that are not elements of B.
a)Design a n O(nlogn) algorithm for solving this problem.
b)Show that the worst-case complexity of your algorithm is O(n logn)
Solution
Part 1
A = {a1, . . . , ak} and B = {b1,. . . , bm}
The required algorithm is given below:
Part 2
Consider array A has k elements and array B has m elements.
Sorting the elements of array B using merge sort results in mlog2m time complexity.
Corresponding to each element of array A a binary search is performed in array B.
Binary search of a single element in an array of size m takes log2m complexity.
So for all the elements of array A, total time complexity due to binary search is k*log2m
Hence total complexity = mlog2m + k*log2m
For the problem lets consider both array A and array B has n elements each.In this case sorting of array B results in nlog2n complexity. And the binary search of n elements of array A in array B one by one results in n * log2n complexity.
So total complexity = nlog2n + nlog2n = 2nlog2n = nlog2n = O(nlogn)
Get Answers For Free
Most questions answered within 1 hours.