Fancy Mouse
- -|||
Exercises
2.2-4 How can we modify almost any algorithm to have a good best-case running time?
CHEAT. Is there any OIer who can not cheat? That's O(1).

2.3-6 Can we use a binary search instead to improve the overall worst-case running time of insertion sort to Θ(nlogn)?
No. Though you can reduce the time of positioning to Θ(logn) for each element, it cannot be changed that the move operation costs Θ(n) in the worst case. So the overall time complexity for insertion sort is still Θ(n^2) for the worst case.

2.3-7 Describe a Θ(nlogn)-time algorithm that, given a set S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x.
First sort the array with any Θ(nlogn) algorithm. Then enumerate each element a[i], search for x-a[i] in the array using the technique of binary search. The overall time complexity is thus Θ(nlogn).

Problems
2-4 Inversions
d. Give an algorithm that determines the number of inversions in any permutation on n elements in Θ(nlogn) worst-case time. (Hint: Modify merge sort.)
There are many solutions to this problem, including a use of segment tree or tree array. Here I just demonstrate an algorithm close to merge sort.
Since the algorithm also follows Divide-and-Conquer approach, we first divide the problem into two subproblems, solve them recursively, just as what merge sort do.
There's a little difference in merging the solutions. When subarray a[1..n] and subarray b[1..m] merges (we assume that a array is prior to b array in position), we pick a smaller element of a[heada] and b[headb] and then heada++ or headb++ respectively. Note that if b[headb] is selected, then b[headb] < a[heada], then for all x>=heada, b[headb] < a[x], when index of b[headb] > a[x], thus (a[x],b[headb]) makes an inversion pair. So simply increase the result by n-heada+1. When a[heada] is selected, no inversion pair is produced.
Thus we can just modify some codes in merge sort to solve the inversion problem. The overall time complexity is Θ(nlogn).
posted on 2007-12-24 21:02  Fancy Mouse  阅读(513)  评论(0编辑  收藏  举报