Algorithms + Data Structures = Programs
一、What is an algorithm?
• A sequence of precise and concise instructions that guide you (or a computer) to solve a class of specific problem
最简单的(straightforward)算法(暴力算法brute force algorithm)可能会运行得很慢,因此我们需要更高效的解决方案
通过观察这个序列是有序的,可以使用更高效的方法——二分查找
二、Well-known Computational Problems
1. Sorting 排序是将一组元素按照某种顺序(通常是升序或降序)排列的过程。
2. Searching 从数据集中查找某一特定元素的过程
3. Graph and Combinatorial Problems
– Shortest paths in a graph 如Dijkstra算法
– Minimum spanning tree 计算一个加权图的最小生成树的问题Prim 和Kruskal算法
– Traveling salesman problem
旅行商问题是寻找一条访问所有节点一次并最终返回到起点的最短路径的问题。
– Knapsack problem
背包问题是选择一组物品,使得它们的总重量不超过限制且总价值最大。
4. Problem in Number Theory
– Primality testing 素数检验是判断一个数是否为素数的问题。
三、Computing the n-th power
Input: a number x & a non-negative integer n
Output: the n-th power of x
Algorithm:
1. Set a temporary variable p to 1.
2. Repeat the multiplication p = p * x for n times.
3. Output the result p.
1. Pseudo Code
(1)Pseudo Code: statement
Assignment statement:variable = expression
e.g., assign the expression 3 * 4 to the variable result:
result = 3 * 4
compound statements
begin
statement1
statement2
end
(2)Pseudo Code: conditional
Conditional statement
if condition then
statement
if a < 0 then
a = -a
abs = a
output abs
if condition then
statement
else
statement
if a > 0 then
abs = a
else
abs = -a
output abs
(3)Pseudo Code: iterative (loop)
Iterative statement
(a) for loop
for var = start_value to end_value do
statement
(b) while loop
condition to CONTINUE the loop
while condition do
statement
this loop is executed for undetermined number of times
(c) repeat-until loop
condition to STOP the loop
repeat
statement
until condition
condition for while loop is NEGATION of condition for repeat-until loop
2. exercise
(1) Find the product of all integers in the interval [x, y], assuming that x and y are both integers
product = 1
For i = x to y do
begin
product = x * product
end
output product
product = 1
i = x
while i <=y do
begin
product = x * product
end
output product
product = 1
i = x
repeat
begin
product = x * product
end
output product
until i>=y
(2) List all factors of a given positive integer x
– e.g., if x is 60, then the output should be 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60
input x
for i = 1 to x do
begin
if x%i = 0 then
output i
end
input x
i = 1
while i<=x do
begin
if x%i = 0 then
output i
end
input x
i = 1
repeat
begin
if x%i = 0 then
output i
end
until i>x