博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法导论(CLRS, 2nd) 个人答案 Ch2.3
阅读量:4463 次
发布时间:2019-06-08

本文共 1970 字,大约阅读时间需要 6 分钟。

2.3-1:

2.3-2:

function MERGE
-
IMPROVED(A,p,q,r){
create array B[
0
... r
-
p];
int
i
=
p, j
=
q
+
1
, t
=
0
;
while
(i
<=
q
&&
j
<=
r){
if
(A[i]
>=
A[j]){
B[t
++
]
=
A[j
++
];
}
else
{
B[t
++
]
=
A[i
++
];
}
}
if
(i
>
q){
//
i pile exhausted
while
(j
<=
r) B[t
++
]
=
A[j
++
];
}
else
if
(j
>
r){
//
j pile exhausted
while
(i
<=
q) B[t
++
]
=
A[i
++
];
}
//
copy the elements back
for
( i
=
0
; i
<=
r
-
q; i
++
){
A[p
+
i]
=
B[i];
}
}

2.3-3:

2.3-4:

//
recursive insertion sort
R_IS(A,s,e){
//
s: start index; e: end index
if
(e
<=
s)
return
;
R_IS(A,s,e
-
1
);
//
here we use linear search; while it's possible to use binary
//
then theoretically, it can achieve a worst time O(n lgn)
for
(
int
i
=
e
-
1
; i
>=
s; i
--
){
if
(A[i]
<
A[e]) swap(A,i,e);
}
}

2.3-5:

/*
@params:
* A: sortted array
* s: starting position
* e: end position
* key: the search key we're looking for
* @return:
* -1 if not found
* one of the index of the key if found
*/
//
binary search recursive
B
-
SEARCH
-
R(
int
A[],
int
s,
int
e,
int
key){
if
(s
>
e)
return
-
1
;
int
mid
=
(s
+
e)
/
2
;
if
(A[mid]
>
key){
return
B
-
SEARCH
-
R(A,s,mid
-
1
,key);
}
else
if
(A[mid]
<
key){
return
B
-
SEARCH
-
R(A,mid
+
1
,e,key);
}
else
return
mid;
}
//
binary search iterative
B
-
SEARCH
-
I(
int
A[],
int
s,
int
e,
int
key){
while
(s
<=
e){
mid
=
(s
+
e)
/
2
;
if
(A[mid]
<
key){
s
=
mid
+
1
;
}
else
if
(A[mid]
>
key){
e
=
mid
-
1
;
}
else
{
return
mid;
}
}
return
mid;
}
/*
Short argue that the run time is O(lg n):
* it's a tree has lg n levels, each level has 1 node.
*/

2.3-6: (updated after the first comment given for this blog post)

We can use a binary search to make it O(n lg n) for search, but cannot improve for moving elements. Therefore, the overall complexity is unchanged.

2.3-7:

(1) merge-sort  -- O(n lg n)

(2) for every element, use binary search to check whether it can form a sum with every  element comes later.

转载于:https://www.cnblogs.com/flyfy1/archive/2011/07/01/2095393.html

你可能感兴趣的文章
WustOJ 1575 Gingers and Mints(快速幂 + dfs )
查看>>
js中,for循环里面放ajax,ajax访问不到变量以及每次循环获取不到数据问题总结...
查看>>
算法:求从1到n这n个整数的十进制表示中1出现的次数-- python 实现
查看>>
CSU 1160 把十进制整数转换为十六进制,格式为0x开头,10~15由大写字母A~F表示
查看>>
LintCode 58: Compare Strings
查看>>
[Unity插件]Lua行为树(五):装饰节点Repeater
查看>>
顺序表、链表、栈和队列
查看>>
Linux第二天(Linux常用命令2)
查看>>
MySql知识体系
查看>>
JIRA中的标记语言的语法参考
查看>>
hdu 6318 Swaps and Inversions(归并排序)
查看>>
用css在IE7、8上实现圆角
查看>>
三维绿幕标定与跟踪
查看>>
android ProgressBar自定义半圆形进度条
查看>>
hdu.5212.Code(莫比乌斯反演 && 埃氏筛)
查看>>
python学习记录一
查看>>
使用LINQ的Skip和Take函数分批获取数据
查看>>
IP通信基础 4月1日
查看>>
KeyProvider
查看>>
空指针为什么能调用成员函数?
查看>>