Correct Algorithm Analysis
Transcript of Correct Algorithm Analysis
Algorithm Analysis
Jordi Cortadella and Jordi Petit
Department of Computer Science
What do we expect from an algorithm?
โข Correct
โข Easy to understand
โข Easy to implement
โข Efficient:
โ Every algorithm requires a set of resources
โข Memory
โข CPU time
โข Energy
Algorithm Analysis ยฉ Dept. CS, UPC 2
Fibonacci: recursive version
// Pre: n 0// Returns the Fibonacci number of order n.
int fib(int n) { // Recursive solution
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);}
Algorithm Analysis ยฉ Dept. CS, UPC 3
Fibonacci
8
7
6
5
4
3
2
1 0
1
2
1 0
3
2
1 0
1
4
3
2
1 0
1
2
1 0
5
4
3
2
1 0
1
2
1 0
3
2
1 0
1
6
5
4
3
2
1 0
1
2
1 0
3
2
1 0
1
4
3
2
1 0
1
2
1 0
How many recursive calls?
Algorithm Analysis ยฉ Dept. CS, UPC 4
Fibonacci: runtime
Algorithm Analysis ยฉ Dept. CS, UPC 5
Fibonacci numbers: iterative version// Pre: n 0// Returns the Fibonacci number of order n.int fib(int n) { // iterative solution
int f_i = 0;
int f_i1 = 1;
// Inv: f_i is the Fibonacci number of order i.
// f_i1 is the Fibonacci number of order i+1.
for (int i = 0; i < n; ++i) {
int f = f_i + f_i1;
f_i = f_i1;
f_i1 = f;
}
return f_i;
}
Algorithm Analysis ยฉ Dept. CS, UPC 6
Runtime: n iterations
Fibonacci numbers
Algebraic solution: find matrix A such that
Algorithm Analysis ยฉ Dept. CS, UPC 7
Fibonacci numbers
Runtime log2 n 2x2 matrix multiplications
Algorithm Analysis ยฉ Dept. CS, UPC 8
Algorithm analysis
Given an algorithm that reads inputs from adomain ๐ท, we want to define a cost function ๐ถ:
where ๐ถ(๐ฅ) represents the cost of using some resource (CPU time, memory, energy, โฆ).
Analyzing ๐ถ ๐ฅ for every possible ๐ฅ is impractical.
Algorithm Analysis ยฉ Dept. CS, UPC 9
Algorithm analysis: simplifications
โข Analysis based on the size of the input: ๐ฅ = ๐
โข Only the best/average/worst cases are analyzed:
๐ ๐ฅ : probability of selecting input ๐ฅamong all the inputs of size ๐.
Algorithm Analysis ยฉ Dept. CS, UPC 10
Algorithm analysis
โข Properties:
โข We want a notation that characterizes the cost of algorithms independently from the technology (CPU speed, programming language, efficiency of the compiler, etc.).
โข Runtime is usually the most important resource to analyze.
Algorithm Analysis ยฉ Dept. CS, UPC 11
Asymptotic notation
Algorithm Analysis ยฉ Dept. CS, UPC 12
Asymptotic notation
Algorithm Analysis ยฉ Dept. CS, UPC 13
๐1๐1(๐)
๐(๐)
๐๐0
๐2๐2(๐)
Asymptotic notation
Algorithm Analysis ยฉ Dept. CS, UPC 14
๐1๐(๐)
๐(๐)
๐๐0
๐2๐(๐)
Asymptotic notation: example
Algorithm Analysis ยฉ Dept. CS, UPC 15
Examples for Big-O and Big-
Algorithm Analysis ยฉ Dept. CS, UPC 16
Complexity ranking
Algorithm Analysis ยฉ Dept. CS, UPC 17
The limit rule
Algorithm Analysis ยฉ Dept. CS, UPC 18
Properties
All rules (except the last one) also apply for and :
โข ๐ โ O ๐
โข โ๐ > 0, O ๐ = O ๐ โ ๐
โข ๐ โ O ๐ ๐ โ O โ ึ ๐ โ O โ
โข ๐1 โ O ๐1 ๐2 โ O ๐2ึ๐1 + ๐2 โ O ๐1 + ๐2 = O(max {๐1, ๐2})
โข ๐ โ O ๐ ึ ๐ + ๐ โ O ๐
โข ๐1 โ O ๐1 ๐2 โ O ๐2 ึ ๐1 โ ๐2 โ O ๐1 โ ๐2
โข ๐ โ O ๐ ึ ๐ โ ฮฉ ๐
Algorithm Analysis ยฉ Dept. CS, UPC 19
Asymptotic complexity (small values)
Algorithm Analysis ยฉ Dept. CS, UPC 20
Asymptotic complexity (larger values)
Algorithm Analysis ยฉ Dept. CS, UPC 21
Execution time: example
Let us consider that every operation can be executed in 1 ns (10-9 s).
Algorithm Analysis ยฉ Dept. CS, UPC 22
How about โbig dataโ?
Algorithm Analysis ยฉ Dept. CS, UPC 23
Source: Jon Kleinberg and รva Tardos, Algorithm Design, Addison Wesley 2006.
This is often the practical limit for big data
The robot and the door in an infinite wall
Algorithm Analysis ยฉ Dept. CS, UPC 24
A robot stands in front of a wall that is infinitely long to the right and left side.The wall has a door somewhere and the robot has to find it to reach the other side.Unfortunately, the robot can only see the part of the wall in front of it.
The robot does not know neither how far away the door is nor what direction totake to find it. It can only execute moves to the left or right by a certain number of steps.
Let us assume that the door is at a distance ๐. How to find the door in a minimum number of steps?
๐
The robot and the door in an infinite wall
Algorithm Analysis ยฉ Dept. CS, UPC 25
๐
Algorithm 1:
โข Pick one direction and move until the door is found.
Complexity:
โข If the direction is correct O(๐).โข If incorrect the algorithm does not terminate.
The robot and the door in an infinite wall
Algorithm Analysis ยฉ Dept. CS, UPC 26
๐
Algorithm 2:โข 1 step to the left, โข 2 steps to the right,โข 3 steps to the left, โฆโข โฆ increasing by one step in the opposite direction.
Complexity:
๐ ๐ =
๐=1
2๐
๐ = 2๐1 + 2๐
2= 2๐2 + ๐ = O(๐2)
The robot and the door in an infinite wall
Algorithm Analysis ยฉ Dept. CS, UPC 27
๐
Algorithm 3:โข 1 step to the left and return to origin,โข 2 steps to the right and return to origin,โข 3 steps to the left and return to origin,โฆโข โฆ increasing by one step in the opposite direction.
Complexity:
๐ ๐ = ๐ + 2
๐=1
๐
๐ = ๐ + 2๐(๐ + 1)
2= ๐2 + 2๐ = O(๐2)
The robot and the door in an infinite wall
Algorithm Analysis ยฉ Dept. CS, UPC 28
๐
Algorithm 4:โข 1 step to the left and return to origin,โข 2 steps to the right and return to origin,โข 4 steps to the left and return to origin,โฆโข โฆ doubling the number of steps in the opposite direction.
Complexity (assume that ๐ = 2๐):
๐ ๐ = ๐ + 2
๐=0
๐
2๐ = ๐ + 2 2๐+1 โ 1 = 5๐ โ 2 = O(๐)
Runtime analysis rules
โข Variable declarations cost no time.
โข Elementary operations are those that can be executed with a small number of basic computer steps (an assignment, a multiplication, a comparison between two numbers, etc.).
โข Vector sorting or matrix multiplication are not elementary operations.
โข We consider that the cost of elementary operations is O 1 .
Algorithm Analysis ยฉ Dept. CS, UPC 29
Runtime analysis rules
โข Consecutive statements:
โ If S1 is O(๐) and S2 is O(๐),then S1;S2 is O(max{๐, ๐})
โข Conditional statements:
โ If S1 is O ๐ , S2 is O ๐ and B is O(โ),then if (B) S1; else S2; is O(max{๐ + โ, ๐ + โ}),
or also O(max{๐, ๐, โ}).
Algorithm Analysis ยฉ Dept. CS, UPC 30
Runtime analysis rules
โข For/While loops:
โ Running time is at most the running time of the statements inside the loop times the number of iterations
โข Nested loops:
โ Analyze inside out: running time of the statements inside the loops multiplied by the product of the sizes of the loops
Algorithm Analysis ยฉ Dept. CS, UPC 31
Nested loops: examplesfor (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)DoSomething(); // O(1)
for (int i = 0; i < n; ++i)for (int j = i; j < n; ++j)
DoSomething(); // O(1)
for (int i = 0; i < n; ++i)for (int j = 0; j < m; ++j)
for (int k = 0; k < p; ++k)DoSomething(); // O(1)
Algorithm Analysis ยฉ Dept. CS, UPC 32
Linear time: O(๐)
Running time proportional to input size
// Compute the maximum of a vector// with n numbers
int m = a[0];
for (int i = 1; i < a.size(); ++i) {
if (a[i] > m) m = a[i];
}
Algorithm Analysis ยฉ Dept. CS, UPC 33
Linear time: O(๐)
Other examples:
โ Reversing a vector
โ Merging two sorted vectors
โ Finding the largest null segment of a sorted vector: a linear-time algorithm exists(a null segment is a compact sub-vector in which the sum of all the elements is zero)
Algorithm Analysis ยฉ Dept. CS, UPC 34
Logarithmic time: O(log ๐)
โข Logarithmic time is usually related to divide-and-conquer algorithms
โข Examples:
โ Binary search
โ Calculating ๐ฅ๐
โ Calculating the ๐-th Fibonacci number
Algorithm Analysis ยฉ Dept. CS, UPC 35
Example: recursive ๐ฅ๐ฆ
// Pre: ๐ โ ๐, ๐ โฅ ๐// Returns ๐๐
int power(int x, int y) {
if (y == 0) return 1;
if (y%2 == 0) return power(xx, y/2);return xpower(xx, y/2);
}
// Assumption: each */% takes O(1)
Algorithm Analysis ยฉ Dept. CS, UPC 36
Linearithmic time: O(๐ log ๐)
โข Sorting: Merge sort and heap sort can be executed in O(๐ log ๐).
โข Largest empty interval: Given ๐ time-stamps ๐ฅ1, โฏ , ๐ฅ๐ on which copies of a file arrive at a server, what is largest interval when no copies of file arrive?
โ O(๐ log ๐) solution. Sort the time-stamps. Scan the sorted list in order, identifying the maximum gap between successive time-stamps.
Algorithm Analysis ยฉ Dept. CS, UPC 37
Selection Sort
โข Selection sort uses this invariant:
Algorithm Analysis ยฉ Dept. CS, UPC 38
-7 -3 0 1 4 9 ? ? ? ? ? ?
ii-1
this is sortedand contains the i-1
smallest elements
this may not be sortedโฆbut all elements here are larger than orequal to the elements in the sorted part
Selection Sortvoid selection_sort(vector<elem>& v) {
int last = v.size() - 1; // v.size() = nfor (int i = 0; i < last; ++i) { // 0..n-2
int k = i;for (int j = i + 1; j <= last; ++j) { // i+1..n-1
if (v[j] < v[k]) k = j;}swap(v[k], v[i]);
}}
Algorithm Analysis ยฉ Dept. CS, UPC 39
Observation: notice that ๐ ๐ โ ฮฉ(๐2), also. Therefore, ๐ ๐ โ ฮ(๐2).
Insertion Sort
โข Let us use inductive reasoning:
โ If we know how to sort arrays of size n-1,
โ do we know how to sort arrays of size n?
Algorithm Analysis ยฉ Dept. CS, UPC 40
9 -7 0 1 -3 4 3 8 -6 8 6 2
-7 -6 -3 0 1 3 4 6 8 8 9 2
n-1n-20
-7 -6 -3 0 1 2 3 4 6 8 8 9
Insertion Sortvoid insertion_sort(vector<elem>& v) {
for (int i = 1; i < v.size(); ++i) { // n-1 timeselem x = v[i];int j = i;while (j > 0 and v[j - 1] > x) { // 0..i times
v[j] = v[j - 1];--j;
}v[j] = x;
}}
Algorithm Analysis ยฉ Dept. CS, UPC 41
The Maximum Subsequence Sum Problem
โข Given (possibly negative) integers ๐ด1, ๐ด2, โฆ , ๐ด๐, find the maximum value of ฯ๐=๐
๐๐ด๐.
(the max subsequence sum is 0 if all integers are negative).
โข Example:โ Input: -2, 11, -4, 13, -5, -2โ Answer: 20 (subsequence 11, -4, 13)
(extracted from M.A. Weiss, Data Structures and Algorithms in C++, Pearson, 2014, 4th edition)
Algorithm Analysis ยฉ Dept. CS, UPC 42
The Maximum Subsequence Sum Problemint maxSubSum(const vector<int>& a) {
int maxSum = 0;// try all possible subsequencesfor (int i = 0; i < a.size(); ++i)for (int j = i; j < a.size(); ++j) {
int thisSum = 0;for (int k = i; k <= j; ++k) thisSum += a[k];if (thisSum > maxSum) maxSum = thisSum;
}return maxSum;
}
Algorithm Analysis ยฉ Dept. CS, UPC 43
The Maximum Subsequence Sum Problem
Algorithm Analysis ยฉ Dept. CS, UPC 44
The Maximum Subsequence Sum Problemint maxSubSum(const vector<int>& a) {
int maxSum = 0;// try all possible subsequencesfor (int i = 0; i < a.size(); ++i) {int thisSum = 0;for (int j = i; j < a.size(); ++j) {
thisSum += a[j]; // reuse computationif (thisSum > maxSum) maxSum = thisSum;
}}return maxSum;
}
Algorithm Analysis ยฉ Dept. CS, UPC 45
Max Subsequence Sum: Divide&Conquer
First half Second half
4 -3 5 -2 -1 2 6 -2
Algorithm Analysis ยฉ Dept. CS, UPC 46
The max sum can be in one of three places:โข 1st halfโข 2nd halfโข Spanning both halves and crossing the middle
In the 3rd case, two max subsequences must be found startingfrom the center of the vector (one to the left and the other tothe right)
Max Subsequence Sum: Divide&Conquer
int maxSumRec(const vector<int>& a,int left, int right) {
// base casesif (left == right)if (a[left] > 0) return a[left];else return 0;
// Recursive cases: left and right halvesint center = (left + right)/2;int maxLeft = maxSumRec(a, left, center);int maxRight = maxSumRec(a, center + 1, right);
โฎ
Algorithm Analysis ยฉ Dept. CS, UPC 47
Max Subsequence Sum: Divide&Conquer
โฎint maxRCenter = 0, rightSum = 0;for (int i = center; i >= left; --i) {rightSum += a[i];if (rightSum > maxRCenter) maxRCenter = rightSum;
}
int maxLCenter = 0, leftSum = 0;for (int i = center + 1; i <= right; ++i) {leftSum += a[i];if (leftSum > maxLCenter) maxLCenter = leftSum;
}
int maxCenter = maxRCenter + maxLCenter;return max3(maxLeft, maxRight, maxCenter);
}
Algorithm Analysis ยฉ Dept. CS, UPC 48
Max Subsequence Sum: Divide&Conquer
Algorithm Analysis ยฉ Dept. CS, UPC 49
We will see how to solve this equation formally in the next lesson(Master Theorem). Informally:
But, can we still do it faster?
The Maximum Subsequence Sum Problem
โข Observations:โ If a[i] is negative, it cannot be the start of the optimal
subsequence.โ Any negative subsequence cannot be the prefix of the optimal
subsequence.
โข Let us consider the inner loop of the O ๐2 algorithm and assume that all prefixes of a[i..j-1] are positive and a[i..j] is negative:
โ If p is an index between i+1 and j, then any subsequence from a[p] is not larger than any subsequence from a[i] and including a[p-1].
โ If a[j] makes the current subsequence negative, we can advance ito j+1.
Algorithm Analysis ยฉ Dept. CS, UPC 50
i p j
a:
The Maximum Subsequence Sum Problem
int maxSubSum(const vector<int>& a) {int maxSum = 0, thisSum = 0;for (int i = 0; i < a.size(); ++i) {
int thisSum += a[i];if (thisSum > maxSum) maxSum = thisSum;else if (thisSum < 0) thisSum = 0;
}return maxSum;
}
Algorithm Analysis ยฉ Dept. CS, UPC 51
4 -3 5 -4 -3 -1 5 -2 6 -3 2
4 1 6 2 0 0 5 3 9 6 8
4 4 6 6 6 6 6 6 9 9 9
a:
thisSum:
maxSum:
Representation of polygons
Algorithm Analysis ยฉ Dept. CS, UPC 52
(1,3)
(4,1)
(7,3)
(5,4)
(6,7)
(2,6)
โข A polygon can be represented by asequence of vertices.
โข Two consecutive vertices representan edge of the polygon.
โข The last edge is represented by thefirst and last vertices of the sequence.
Vertices: (1,3) (4,1) (7,3) (5,4) (6,7) (2,6)
Edges: (1,3)-(4,1)-(7,3)-(5,4)-(6,7)-(2,6)-(1,3)
// A polygon (an ordered set of vertices)using Polygon = vector<Point>;
Create a polygon from a set of points
Algorithm Analysis ยฉ Dept. CS, UPC 53
Given a set of ๐ points in the plane, connect them in a simple closed path.
Simple polygon
โข Input: ๐1, ๐2, โฆ , ๐๐ (points in the plane).
โข Output: P (a polygon whose vertices are ๐1, ๐2, โฆ , ๐๐ in some order).
โข Select a point ๐ง with the largest ๐ฅcoordinate (and smallest ๐ฆ in case of a tie in the ๐ฅ coordinate). Assume ๐ง = ๐1.
โข For each ๐๐ โ {๐2, โฆ , ๐๐}, calculate the angle ๐ผ๐ between the lines ๐ง โ ๐๐ and the ๐ฅ axis.
โข Sort the points {๐2, โฆ , ๐๐} according to their angles. In case of a tie, use distance to ๐ง.
Algorithm Analysis ยฉ Dept. CS, UPC 54
๐ง
Simple polygon
Implementation details:
โข There is no need to calculate angles(requires arctan). It is enough to calculate slopes ( ฮคฮ๐ฆ ฮ๐ฅ).
โข There is not need to calculate distances. It is enough to calculate the square of distances (no sqrt required).
Complexity: O(๐ log ๐).The runtime is dominated by the sorting algorithm.
Algorithm Analysis ยฉ Dept. CS, UPC 55
๐ง
Convex hull
Algorithm Analysis ยฉ Dept. CS, UPC 56
Compute the convex hull of ๐ given points in the plane.
๐ผ
๐ฝ
๐ผ < ๐ฝ
Clockwise and counter-clockwise
Algorithm Analysis ยฉ Dept. CS, UPC 57
How to calculate whether three consecutive verticesare in a clockwise or counter-clockwise turn.
counter-clockwise(๐๐ at the left of ๐๐๐๐)
๐1
๐2
๐3
๐1
๐2๐3
// Returns true if ๐3 is at the left of ๐1๐2bool leftof(๐1, ๐2, ๐3) {return ๐2. ๐ฅ โ ๐1. ๐ฅ โ ๐3. ๐ฆ โ ๐1. ๐ฆ > ๐2. ๐ฆ โ ๐1. ๐ฆ โ (๐3. ๐ฅ โ ๐1. ๐ฅ);
}
๐ฝ๐ผ
๐ผ > ๐ฝ
clockwise(๐๐ at the right of ๐๐๐๐)
Convex hull: gift wrapping algorithm
Algorithm Analysis ยฉ Dept. CS, UPC 58
https://en.wikipedia.org/wiki/Gift_wrapping_algorithm
Convex hull: gift wrapping algorithmโข Input: ๐1, ๐2, โฆ , ๐๐ (points in the plane).
โข Output: P (the convex hull of ๐1, ๐2, โฆ , ๐๐).
โข Initial points:๐0 with the smallest ๐ฅ coordinate.
โข Iteration: Assume that a partial path with ๐ points has been built ( ๐๐ is the last point). Pick some arbitrary ๐๐+1 โ ๐๐. Visit the remaining points.If some point ๐ is at the left of ๐๐๐๐+1 redefine ๐๐+1 = ๐.
โข Stop when P is complete (back to point ๐0).
Algorithm Analysis ยฉ Dept. CS, UPC 59
Complexity: At each iteration, we calculate ๐ angles. ๐ ๐ = ๐(โ๐), where โ is the numberof points in the convex hull. In the worst case, ๐ ๐ = O ๐2 .
๐0
๐๐
๐๐+1
๐๐โ1
Convex hull: gift wrapping algorithmvector<Point> convexHull(vector<Point> points) {int n = points.size();vector<Point> hull;
// Pick the leftmost pointint left = 0;for (int i = 1; i < n; i++)if (points[i].x < points[left].x) left = i;
int p = left;do {hull.push_back(points[p]); // Add point to the convex hull
int q = (p + 1)%n; // Pick a point different from pfor (int i = 0; i < n; i++)if (leftof(points[p], points[q], points[i])) q = i;
p = q; // Leftmost point for the convex hull} while (p != left); // While not closing polygon
return hull;}
Algorithm Analysis ยฉ Dept. CS, UPC 60
Convex hull: Graham Scan
Algorithm Analysis ยฉ Dept. CS, UPC 61
https://en.wikipedia.org/wiki/Graham_scan
Convex hull: Graham scan
Input: ๐1, ๐2, โฆ , ๐๐ (points in the plane).
Output: ๐1, ๐2, โฆ , ๐๐ (the convex hull).
Initially:Create a simple polygon P (complexity O(๐ log ๐)).Assume the order of the points is ๐1, ๐2, โฆ , ๐๐.
Algorithm Analysis ยฉ Dept. CS, UPC 62
// ๐ = (๐1, ๐2, โฆ ) is a vector where the points// of the convex hull will be stored.๐1 = ๐1; ๐2 = ๐2; ๐3 = ๐3; ๐ = 3;for ๐ = 4 to ๐:while leftof(๐๐โ1, ๐๐ , ๐๐): ๐ = ๐ โ 1;๐ = ๐ + 1;๐๐ = ๐๐;
๐1
๐๐
๐๐โ1
๐๐
Observation: each point ๐๐ can be included in ๐ and deleted at most once.The main loop of Graham scan has linear cost.Complexity: dominated by the creation of the simple polygon ๐(๐ log ๐).
EXERCISES
Algorithm Analysis ยฉ Dept. CS, UPC 63
Summations
Prove the following equalities:
๐=1
๐
๐ =๐(๐ + 1)
2
๐=1
๐
๐2 =๐(๐ + 1)(2๐ + 1)
6
๐=0
๐
2๐ = 2๐+1 โ 1
Algorithm Analysis ยฉ Dept. CS, UPC 64
For loops: analyze the cost of each code// Code 1int s = 0;for (int i = 0; i < n; ++i) ++s;
// Code 2int s = 0;for (int i = 0; i < n; i += 2) ++s;
// Code 3int s = 0;for (int i = 0; i < n; ++i) ++s;for (int j = 0; j < n; ++j) ++s;
// Code 4int s = 0;for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) ++s;}
// Code 5int s = 0;for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) ++s;}
Algorithm Analysis ยฉ Dept. CS, UPC 65
For loops: analyze the cost of each code// Code 6int s = 0;for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) ++s;}
// Code 7int s = 0;for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {for (int k = 0; k < n; ++k) ++s;
}}
// Code 8int s = 0;for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {for (int k = 0; k < j; ++k) ++s;
}}
Algorithm Analysis ยฉ Dept. CS, UPC 66
For loops: analyze the cost of each code// Code 9int s = 0;for (int i = 1; i <= n; i = 2) ++s;
// Code 10int s = 0;for (int i = 0; i < n; ++i) {for (int j = 0; j < ii; ++j) {
for (int k = 0; k < n; ++k) ++s;}
}
// Code 11int s = 0;for (int i = 0; i < n; ++i) {for (int j = 0; j < ii; ++j) {
if (j%i == 0) {for (int k = 0; k < n; ++k) ++s;
}}
}
Algorithm Analysis ยฉ Dept. CS, UPC 67
O, ฮฉ or ฮ?
The following statements refer to the insertion sort algorithm and the Xโs hide an occurrence of O, ฮฉ or ฮ. For each statement, find which options for ๐ โ {O, ฮฉ, ฮ} make the statement true or false. Justify your answers.
1. The worst case is ๐(๐2)2. The worst case is ๐(๐)3. The best case is ๐(๐2)4. The best case is ๐(๐)5. For every probability distribution, the average case is ๐(๐2)6. For every probability distribution, the average case is ๐(๐)7. For some probability distribution, the average case is ๐(๐ log ๐)
Algorithm Analysis ยฉ Dept. CS, UPC 68
PrimalityThe following algorithms try to determine whether ๐ โฅ 0 is prime. Find which ones are correct and analyze their cost as a function of ๐.
Algorithm Analysis ยฉ Dept. CS, UPC 69
bool isPrime1(int n) {if (n <= 1) return false;for (int i = 2; i < n; ++i) if (n%i == 0) return false;return true;
}
bool isPrime2(int n) {if (n <= 1) return false;for (int i = 2; ii < n; ++i) if (n%i == 0) return false;return true;
}
bool isPrime3(int n) {if (n <= 1) return false;for (int i = 2; ii <= n; ++i) if (n%i == 0) return false;return true;
}
bool isPrime4(int n) {if (n <= 1) return false;if (n == 2) return true;if (n%2 == 0) return false;for (int i = 3; ii <= n; i += 2) if (n%i == 0) return false;return true;
}
The Sieve of Eratosthenes
The following program is a version of the Sieve of Eratosthenes. Analyze its complexity.
Algorithm Analysis ยฉ Dept. CS, UPC 70
vector<bool> Primes(int n) {vector<bool> p(n + 1, true);p[0] = p[1] = false;for (int i = 2; i*i <= n; ++i) {if (p[i]) {for (int j = i*i; j <= n; j += i) p[j] = false;
}}return p;
}
You can use the following equality, where ๐ โค ๐ฅ refers to all primes ๐ โค ๐ฅ:
๐โค๐ฅ
1
๐= log log ๐ฅ + O(1)
The Cell Phone Dropping Problem
โข You work for a cell phone company which has just invented a new cell phone protector and wants to advertise that it can be dropped from the ๐th floor without breaking.
โข If you are given 1 or 2 phones and an ๐ story building, propose an algorithm that minimizes the worst-case number of trial drops to know the highest floor it wonโt break.
โข Assumption: a broken cell phone cannot be used for further trials.
โข How about if you have ๐ cell phones?
(Source: Wood & Yasskin, Texas A&M University)
Algorithm Analysis ยฉ Dept. CS, UPC 71
๐