0% found this document useful (0 votes)
1 views

01-intro

Uploaded by

zhouxiaochao7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

01-intro

Uploaded by

zhouxiaochao7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

THREE REASONS TO STUDY

ALGORITHMS

THEORY OF ALGORITHMS
1. Predict running time of an
algorithm based on input size
(Analysis).
How long to sort 300 million names ?

1 void insertion_sort(vector<string> &V)


2 {
3 for (int i = 1; i < V.size(); ++i)
4 for (int j = i; j > 0 && V[j] < V[j-1]; --j)
5 swap(V[j], V[j-1]);
6
7 }

2
Answer

Assuming 3 billion comparisons can be compared each second,

(3 · 108 )(3 · 108 − 1)


≈ 0.47 years
(2)(3 · 109 )(31536000)

3
How long does f(100) take ?

1 unsigned f(unsigned n)
2 {
3 if (n == 0)
4 return 0;
5 return 1 + f(n-1) + f(n-1);
6 }

4
Answer

2100
≈ 957 times universe age
(3 · 109 )(31536000)(14 · 109 )

5
Which algorithm is faster ?
Try: a = 3210987654; b = 2109876543

1 uint gcd1(uint a, uintb) 1 uint gcd2(uint a, uint b)


2 { 2 {
3 for (uint d = min(a, b); d > 0; --d) 3 while (b > 0)
4 if (a % d == 0 && b % d == 0) 4 {
5 return d; 5 uint temp = b;
6 6 b = a % b;
7 7 a = temp;
8 8 }
9 9 return a;
10 } 10 }

6
2. Given a problem, design an
algorithm to solve it.
Design an algorithm for this problem

input: a positive integer N;



output: ⌊ N ⌋.

7
Answer

Want:largest integer whose square is at most N .


Exhaustively try all candidates between 1 and N .
1 int exhaustive_search(int N)
2 {
3 for (int i = 1; i <= N; ++i)
4 if (i*i > N)
5 return i-1;
6
7 }

8
Design an algorithm for this problem

input: integers b and e ;


output: be .

9
Answer

Use recursion:


(b(e /2) )2 if e is even
be =
b · be −1 otherwise.

1 int divide_conquer(int b, int e)


2 {
3 if (e == 0)
4 return 1;
5
6 if (e % 2 == 0)
7 {
8 int temp = divide_conquer(b, e/2);
9 return temp * temp;
10 }
11 else
12 return b * divide_conquer(b, e-1);
13 }

10
Design an algorithm for this problem

input: integers a and b;


output: the least common multiple of a and b.

11
Answer

Transform problem to another problem whose solution is known:

lcm(a, b) = gcdab
(a, b)
.

1 int transform_conquer(int a, inb )


2 {
3 return (a*b)/gcd(a, b);
4 }

12
3. Determine the minimum time
required to solve a given problem
Sorting

We know many sorting algorithms: insertion, selection, merge,


heap, quick.

Is there a faster solution not yet discovered ?

13
Answer

merge sort/heap sort is the fastest possible sorting algorithm (up to


a multiplicative constant, and if only comparisons are allowed.)

14

You might also like