Non Recursive Algorithm
Non Recursive Algorithm
Dr. Ying Lu
[email protected]
September 6, 2012
*slides refrred to
http://www.aw-bc.com/info/levitin
1
Time efficiency of nonrecursive algorithms
2
Time efficiency of nonrecursive algorithms
3
Series
N
N ( N 1)
S i
i 1 2
Proof by Gauss when 9 years old (!):
S 1 2 3 ... ( N 2) ( N 1) N
S N ( N 1) ( N 2) ... 3 2 1
2 S N ( N 1)
4
General rules for sums
c ?
i m
5
General rules for sums
n n
c c1 c(n m 1)
i m i m
(a b ) a b
i
i i
i
i
i
i
ca
i
i c ai
i
n nk
a
i m
ik a
i m k
i
a x
i
i
ik
x k
a xi
i
i
6
Examples:
Matrix multiplication
• Section 2.3
Selection sort
• Section 3.1
Insertion sort
• Section 4.1
7
Matrix multiplication
MatrixMultiplication(A[0..n-1, 0..n-1], B[0..n-1, 0..n-1])
Input: two n-by-n matrices A and B
Output: C = A * B
- - - -
=
-
-
-
8
Sorting problem
Given a list of n orderable items, rearrange them
in a non-decreasing order
9
Sorting problem
10
Selection sort
-
-
-
11
Sorting problem
12
Insertion sort
-
-
-
-
13
In-class exercises
P67 2.3.1 (c) & (d)
14
In-Class Exercises
Problem 12: Door in a wall You are facing a wall that
stretches infinitely in both directions. There is a door in the
wall, but you know neither how far away nor in which
direction. You can see the door only when you are right next
to it. Design an algorithm that enables you to reach the
door. How many steps will it require?
15
Solution 1
Walk right and left going each time one step farther from the
initial position. A simple implementation of this idea is to do
the following until the door is reached: For i = 0, 1, ..., make i
steps to the right, return to the initial position, make i steps to
the left, and return to the initial position again.
How many steps will this algorithm require to find the door?
Does it require walking at most O(n) steps where n is the
(unknown to you) number of steps between your initial
position and the door.
16
Solution 2
Walk intermittently right and left going each time
exponentially farther from the initial position. A simple
implementation of this idea is to do the following until the door
is reached: For i = 0, 1, ..., make 2i steps to the right, return to
the initial position, make 2i steps to the left, and return to the
initial position again. Let 2k−1 < n ≤ 2k.
How many steps will this algorithm require to find the door?
Does it require walking at most O(n) steps where n is the
(unknown to you) number of steps between your initial
position and the door.
17