Sorting Question
Sorting Question
Class: 22CLC01/22CLC07
CHAPTER 2 – PROBLEMS
Problem 1. a. Give an example of an algorithm that should not be considered an
application of the brute-force approach.
b. Give an example of a problem that cannot be solved by a brute-force
algorithm.
Problem 2. Is it possible to implement selection sort for linked lists with the same 𝑂(𝑛2 )
efficiency as the array version?
Problem 3. Alternating disks You have a row of 2n disks of two colors, n dark and n light.
They alternate: dark, light, dark, light, and so on. You want to get all the dark disks to the
right-hand end, and all the light disks to the left-hand end. The only moves you are
allowed to make are those that interchange the positions of two neighboring disks.
Design an algorithm for solving this puzzle and determine the number of moves it takes.
Does your algorithm follow a brute-force approach?
b. Solve the same problem if 2n glasses—n with a drink and n empty—are initially
in a random order.
Problem 5. Compare the slide’s implementation of insertion sort with the following
version.
ALGORITHM INSERTION-SORT2(A[0…n-1])
for i 1 to n – 1 do
j i – 1
while j ≥ 0 and A[j] > A[j+1] do
swap(A[j], A[j+1])
j j – 1
What is the time efficiency of this algorithm? How is it compared to that of the version
given in the slide?
Problem 8. Give an example showing that quicksort is not a stable sorting algorithm.
Problem 9. What is the running time of Quicksort when all elements of array A have the
same value?
Problem 10. Show that, with the array representation for storing an n-element heap, the
leaves are the nodes indexed by ⌊𝑛/2⌋, ⌊𝑛/2⌋ + 1, … , 𝑛 − 1.
Problem 12. Suppose that we were to rewrite the for loop in line 7 of the Counting-Sort
in the slide as
7. for i 0 to n – 1
Show that the algorithm still works properly, but that is not stable.
Problem 13. Describe an algorithm that, given n integers in the range 0 to k, preprocesses
its input and then answers any query about how many of the n integers fall into a range
[a : b] in O(1) time. Your algorithm should use 𝑂(𝑛 + 𝑘) preprocessing time.