Shellsort
1.确定一个递减的序列
2.对于序列第i个元素hi,从数组的头开始到尾,总是对j,j+hi,j+2hi,...排序
3.对于整个序列,重复2
最差情况O(N^2),如果使用希尔递增,最坏和平均都可以减小到O(N)和O(N^2)之间的一个值
Heapsort
1.对于数组,对第n/2个元素到第1个元素执行PercDown操作(总是选一个最小的孩子和它交换,直到叶子或者孩子都比它大)
2.将最小的元素删除,最后一个元素放入堆顶,进行PercDown操作
3.把删除的元素放入排序数组
4.重复2,3直到堆空
建堆复杂度O(N),删除最小的复杂度O(logN),删除N个,O(NlogN),所以复杂度为O(NlogN)
算法2:
1.建大顶堆
2.交换堆底和堆顶的元素
3.堆顶元素执行PrecDown操作(注意此时被交换下来的元素虽然在数组中,但是不属于堆,不参加交换)
4.对于n-1到1的元素执行3
Mergesort
Msort
1.如果right<left,退出
2.Center = (left+right)/2
3.Msort(a,left,center)
4.Msort(a,center+1,right)
5.Merge(a,left,center+1,right)
Merge
input:左子列开始Lpos,右子列开始Rpos,右子列结束Rend
1.计算左子列结束:Lend=Rpos-1
2.i=Lpos,j=Rpos,k= Lpos
3.比较i,j指向的元素大小,将小的放入临时数组,并使对应下标++,k++
4.如果i<=Lend或j<=Rend,重复3
5.如果i<=Lend,将i到Rend拷贝进临时数组
6.如果j<=Rend,将j到Lend拷贝进临时数组
7.将临时数组拷贝进a的Lpos到Rend
复杂度:归并为O(N),递归为(NlogN),总共为O(N+NlogN)
题目
1.Shell sort is stable.
稳定是指相同的元素在排序前后的顺序是不变的。
凡是有前后两个元素交换的算法都是不稳定的。
F
2.Mergesort is stable.
MergSort只涉及到按顺序赋值,没有前后元素的交换。T
3.To sort N records by merge sort, the number of merge runs is O(NlogN).
merge运行了logN次,F
4.To sort { 8, 3, 9, 11, 2, 1, 4, 7, 5, 10, 6 } by Shell Sort, if we obtain ( 4, 2, 1, 8, 3, 5, 10, 6, 9, 11, 7 ) after the first run, and ( 1, 2, 3, 5, 4, 6, 7, 8, 9, 11, 10 ) after the second run, then the increments of these two runs must be _B_ , respectively.
A.3 and 1
B.3 and 2
C.5 and 2
D.5 and 3
找位置发生变换的元素,位置只差最小的就是increment
5.To sort N elements by heap sort, the extra space complexity is:A
A.O(1)
B.O(logN)
C.O(N)
D.O(NlogN)
用大顶堆删最大元素法,不需要额外的空间。
6.To sort N records by merge sort, the worst-case time complexity is:C
A.O(logN)
B.O(N)
C.O(NlogN)
D.O(N2)
7.To sort { 49, 38, 65, 97, 76, 13, 27, 50 } in increasing order, which of the following is the result after the 1st run of Shell sort with the initial increment 4?
A.13,27,38,49,50,65,76,97
B.49,13,27,50,76,38,65,97
C.49,76,65,13,27,50,97,38
D.97,76,65,50,49,38,27,13
B,只需要按照元素下标加4的进行排序
8.Given input {15, 9, 7, 8, 20, -1, 4}. If the result of the 1st run of Shell sort is {15, -1, 4, 8, 20, 9, 7}, then the initial increment must be:D
A.1
B.2
C.3
D.4
7.Given an integer sequence 25、84、21、47、15、27、68、35、20, after the first run of the shell sorting by an increment 3, the integer sequence is __.
A.25 15 20 27 35 21 68 84 47
B.15 21 20 25 84 27 68 35 47
C.25 15 20 47 21 35 68 84 27
D.25 15 20 47 35 21 68 84 27
看1,4,7和0,3,6选D