
Exercises related to Sorting
1. Suppose that Sis a set of nintegers. Describe an efficient algorithm to
determine whether there are two (or more) equal integers in S. What
is the running time of your algorithm?
(Note: This can easily be done in time O(n2). (How?) Can you do
better?)
2. Give a sequence of nintegers with ā¦(n2) inversions. (Recall the defi-
nition of an inversion from the class notes.)
3. Suppose you are given two sequences Xand Yof kintegers each,
possibly containing duplicates. Describe an efficient algorithm to de-
termine if Xand Ycontain the same set of elements (possibly in
different orders). What is the running time of your procedure?
(Note: There are two ways this could be interpreted. Suppose that
X= (1,1,1,1,2) and Y= (2,2,1,2,1). If we take only the collection
of distinct elements into account, then since Xand Yboth contain
1 and 2 (only ācountingā a duplicated item once), we might consider
them to ācontain the same set of elementsā. If, on the other hand, we
want to consider both the elements and the number of occurrences,
then Xand Yare do not contain the same set of elements, as the
number of occurrences of 1 and 2 in the lists are clearly different.
Consider both of these cases in your analysis.)
4. Bob has a set Aof nnuts and a set Bof nbolts, such that each nut
in Ahas a unique matching bolt in B. Unfortunately, the nuts in A
all look the same, and the bolts in Ball look the same as well. The
only kind of comparison that Bob can make is to take a nut-bolt pair
(a, b) (such that aāAand bāB) and test them to see if the threads
of aare larger, smaller, or a perfect match with the threads of b.
Describe an efficient algorithm for Bob to match up all of the nuts
and bolts. What is the running time of this algorithm, in terms of the
number of nut-bolt comparisons that Bob must make?
5. Let Aand Bbe two sequences, each having kintegers. Given an
integer x, describe an O(klog k) algorithm to determine if there is an
integer ain Aand an integer bin Bsuch that x=a+b.
1