Chapter 2 Exercises and Problems

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).

转载于:https://www.cnblogs.com/FancyMouse/articles/1013169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值