Equal number of nuts and bolts of various sizes are given. There is a match for every bolt in the set of the nuts. Comparisom of a bolt with a bolt and a nut with a nut is prohibited. How to make ut bolt pairs in shortest possible time?
We can use divide and conquer here. We cannot sort only nuts ( only bolts ) according to size because nut-nut (bolt-bolt ) comparison is prohibited.
So we try to match a nut with bolts. Three conditions arise :
a. Its a match.
b. Bolt is smaller.
c. Bolt is bigger.
Now we can divide bolts in two parts: smaller ones and bigger ones. The matching nut-bolt (pivot elements) are the first match.
Now try to match the pivot bolt with remaining nuts. Two conditions arise :
a. Nut is smaller.
b. Nut is bigger.
Now we can divide nuts in two parts: smaller ones and the bigger ones.
The set of smaller nuts have a match in the set of smaller bolts and vice versa.
So after ~2n (assuming n nuts and n bolts) comparisons the bigger problem is divided into 2 smaller problems of half size (~ n/2).
Hence the time complexity is:
T(n)= T(n/2)+ O(n) ~ O(n lg n).
No comments:
Post a Comment