DSA2 - Chap1 - General Overview
DSA2 - Chap1 - General Overview
Chapter 1
Programming : A General Overview
❖ Introduction
❖ Mathematics Review
- Exponent
- Logarithms
- Series
- Proofs
• Proof By Induction
- Sum of arithmetic serie
- Sum of squares
- Fibonacci numbers
• Proof By Counter Example
• Proof By Contradiction
❖ Recursion
- Recursion vs Iteration
3
Introduction
What Is an Algorithm?
Example
Problem : determine the kth largest number in a group of
N numbers.
Selection problem
4
Introduction
Selection problem
Algorithm 1
Introduction
Selection problem
Algorithm 2
- read the first k elements into an array and
sort them (in decreasing order).
Introduction
Mathematics Review
Exponents
XA XB = XA+B
2N +2N = 2N+1
10
Mathematics Review
Logarithms
In computer science, all logarithms are to the base 2 unless
specified otherwise :
XA = B if and only if logx B = A
Arithmetic series
Each term in an arithmetic series is increased by a constant value
(usually 1) :
Proof 1: write out the series twice and add each column
1 + 2 + 3 + ... + n – 2 + n – 1 + n
+ n + n – 1 + n – 2 + ... + 3 + 2 + 1
(n + 1) + (n + 1) + (n + 1) + . . . + (n + 1) + (n + 1) + (n + 1)
= n (n + 1)
Since we added the series twice, we must divide the result by 2
Mathematics Review 12
Geometric series
The next series we will look at is the geometric series with common
ratio r:
Geometric series
proof : multiply by
Telescoping series:
all but the first and last terms cancel
14
Geometric series
Proofs
The two most common ways of proving statements in data-structure
analysis are proof by induction and proof by contradiction .
1 + 22 + 32 +.........n2 =
F0 = 1, F1 = 1
F2 = 2 , F3 = 3 , F4 = 5
Fk+1 = Fk + Fk-1
Proof by Counterexample
Example: is FN < N2 ?
Proof by Contradiction
Proof by Contradiction
We assume that the theorem is false,
the number of primes is finite, k. So that The largest prime is Pk
Let P1, P2, ... , Pk be all the primes
Consider the number N = 1 + P1 * P2* ..... * Pk
N is larger than Pk , thus N is not prime (hypothesis)
So N must be the product of some primes.
However, none of the primes P1, P2 , ... , Pk divide N exactly.
So N is not a product of primes. (contradiction)
1. int f( int x )
2. {
3. if( x == 0 )
4. return 0;
5. else
6. return 2 * f( x - 1 ) + x * x;
7. }
1. Base cases. You must always have some base cases, which can be
solved without recursion.
Example 2 : Factorial
To evaluate factorial(n)
factorial(n) = n*(n-1)*...*2* 1
= n * factorial(n-1)
Example 2 : Factorial
Need to move all k disks to the destination peg using the auxiliary
peg, without ever keeping a bigger disk on the smaller disk.
31
Introduction to recursion
Tower of Hanoi(k, source, auxiliary, destination)
{
If k=1 move disk from source to destination; (base case)
Else,
{
Tower of Hanoi(top k-1, source, destination,
auxiliary);
Move the kth disk from source to destination;
Tower of Hanoi(k-1, auxiliary, source, destination);
}
}