Decrease-and-Conquer-10
Decrease-and-Conquer分为两种
和Devide-and-Conquer的区别在于Decrease-and-Conquer只解决一个实例,而Devide-and-Conquer解决很多相同的子实例
- Decrease-and-Conquer by-a-Constant
In this approach, the size of the problem is reduced by some constant in each iteration of the algorithm.包含
- Insertion Sort
- topological sorting
- Decrease-and-Conquer by-a-Factor
- Decrease-by-a-constant-factor
binary search - Decrease-by-a-variable-factor
interpolation search
5.1Insertion Sort
- 步骤:
1.sort the first n − 1 items, then
将前n-1个元素排好序
2.locate the cell that should hold the last item,
shift all elements to its right to the right, and
place the last element.
将最后一个元素与前面的元素做对比,若最后一个元素小于对比的元素,则对比的元素往后移,直至找到小于最后一个元素的值,并将最后一个元素放入这个元素之后。
Insertion Sort总结
1.最差时间复杂度和平均时间复杂度都为Theta(n^2),当数组为逆向排序时
2.但时间复杂度为Theta(n),当数组为 almost-sorted input。
3.有的数组的-1或0或最后一个位置会为空,用来放置哨兵post a sentinel,放置最小值,用以结束循环,可以将排序的速度提高一个常数,但不改变Theta其仍为n^2
4.Insertion Sort易于理解应用
5.适用于小的数组
6.Insertion Sort是stable的,是in-place的
7.decrease-and-conquer by a constant
5.2 Shellsort: Motivation
间隔选择:
1.从最大的k开始,然后用小一点的ks,若为小数组则选用2/3最佳
2.认为1、4、13、40、121、364、1093是最好的间隔选择,n=n*3+1,但也要考虑运行的次数(例20000应该选择364,虽然1093是可以容纳的更大间隔数,但要做1093次Insertion Sort)
- 步骤
1.可以把这个数组看作是k个列表的交错
2.使用插入排序分别对每个列表进行排序
3.然后使用最后一次插入排序对得到的整个数组进行排序
Shellsort总结
1.相较于 insertion sort来说比较次数更少,选择最好间隔差时(n=n3+1)的最差时间复杂度为* O(n^1.5).
2.猜想时间复杂度有可能接近O(n^1.25).
3.Shellsort不是stable的,是in-place的**
5.3Binary Search
This is a well-known approach for searching for an element k in a sorted array
- 步骤
1.首先与数组的中间元素A[m]进行比较。
2.如果A[m] = k,就做完了。
3.如果A[m] >k,递归搜索子数组直到A[m−1]。
4.如果A[m]
Binary Search总结
1.最差时间复杂度为Theta(log2(n)),当要找的k不在队列的时候是最差的情况。
2.平均时间复杂度为Theta(logn)
5.4Russian Peasant Multiplication
5.5Lomuto Partitioning分区
用于找中间值,或者第几小的值
Partitioning an array around some pivot element p means reorganizing the array so that all elements to the left of p are no greater than p, while those to the right are no smaller. 分区,将小于p的放置在左边,大于等于p的放在右边
5.4Quickselect
Finding the kth-smallest Element
- 步骤
1.利用Lomuto Partitioning,将数组A的第一个元素找到其是第几小的值(设为m)
2.将A按照m分为两个部分,若要找的k小于m在前一部分找,若要找的k大于m在后一部分找,重复1
Quickselect 总结
1.最差时间复杂度为Theta(n^2),当数组已经排好序时
2.平均时间复杂度为Theta(n)
3.Quickselect是stable的,是in-place的
5.5Interpolation Search
总结
1.适用于数组是已经排好序的情况
2.适用于非均匀分布的大数组
3.找到要找的k更靠近最大值还是最小值