Introduction to Algorithms

Slides:



Advertisements
Similar presentations
CS3024-FAZ1 Mathematical Analysis of Recursive Algorithms Design and Analysis of Algorithms (CS3024) 28/02/2006.
Advertisements

Algorithm Design Techniques
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Copyright © 2007 Pearson Addison-Wesley. All rights reserved. A. Levitin Introduction to the Design & Analysis of Algorithms, 2 nd ed., Ch. 1 Chapter 2.
The Tower Of Hanoi Edouard Lucas
Starting Out with Java: From Control Structures through Objects
Chapter 11 Limitations of Algorithm Power Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 3 Brute Force Brute force is a straightforward approach to solving a problem, usually directly based on the problem’s statement and definitions.
Chapter 2 Fundamentals of the Analysis of Algorithm Efficiency Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Analyzing Algorithms and Problems Prof. Sin-Min Lee Department of Computer Science.
Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 2 Some of the sides are exported from different sources.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
1 Recursive Algorithm Analysis Dr. Ying Lu RAIK 283: Data Structures & Algorithms September 13, 2012.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Chapter 2 Fundamentals of the Analysis of Algorithm Efficiency Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Design and Analysis of Algorithms - Chapter 21 Analysis of Algorithms b Issues: CorrectnessCorrectness Time efficiencyTime efficiency Space efficiencySpace.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Chapter 2: Fundamentals of the Analysis of Algorithm Efficiency
Chapter 8 With Question/Answer Animations 1. Chapter Summary Applications of Recurrence Relations Solving Linear Recurrence Relations Homogeneous Recurrence.
Copyright © Cengage Learning. All rights reserved.
Lecture 6 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Advanced Counting Techniques
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
Chapter 8. Section 8. 1 Section Summary Introduction Modeling with Recurrence Relations Fibonacci Numbers The Tower of Hanoi Counting Problems Algorithms.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Design and Analysis of Algorithms - Chapter 21 Analysis of Algorithms b Issues: CorrectnessCorrectness Time efficiencyTime efficiency Space efficiencySpace.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Fall 2015 COMP 2300 Discrete Structures for Computation Donghyun (David) Kim Department of Mathematics and Physics North Carolina Central University 1.
Analysis of Algorithm Efficiency Dr. Yingwu Zhu p5-11, p16-29, p43-53, p93-96.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Lecture 5 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Discrete Mathematics Recurrence Relations Chapter 5 R. Johnsonbaugh
Copyright © 2007 Pearson Addison-Wesley. All rights reserved. A. Levitin “ Introduction to the Design & Analysis of Algorithms, ” 2 nd ed., Ch. 1 Chapter.
2-0 Copyright © 2007 Pearson Addison-Wesley. All rights reserved. A. Levitin “ Introduction to the Design & Analysis of Algorithms, ” 2 nd ed., Ch. 2 Theoretical.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 2 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
1 UNIT-I BRUTE FORCE ANALYSIS AND DESIGN OF ALGORITHMS CHAPTER 3:
RECURRENCE Sequence Recursively defined sequence
Discrete Mathematics Lecture # 22 Recursion.  First of all instead of giving the definition of Recursion we give you an example, you already know the.
1 RECURRENCE 1. Sequence 2. Recursively defined sequence 3. Finding an explicit formula for recurrence relation.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Mathematical Analysis of Recursive Algorithm CSG3F3 Lecture 7.
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Chapter 2 Fundamentals of the Analysis of Algorithm Efficiency Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Theoretical analysis of time efficiency
Analysis of Algorithms
Analysis of algorithms
Design and Analysis of Algorithms Chapter -2
Introduction to the Design and Analysis of Algorithms
Decrease-and-Conquer Approach
Introduction to Recurrence Relations
Analysis of algorithms
Introduction to the Design and Analysis of Algorithms
Chapter 2 Fundamentals of the Analysis of Algorithm Efficiency
Chapter 2 Fundamentals of the Analysis of Algorithm Efficiency
Chapter 2 Fundamentals of the Analysis of Algorithm Efficiency
Chapter 3 Brute Force Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Copyright © Cengage Learning. All rights reserved.
Algorithm Efficiency and Sorting
Copyright © Cengage Learning. All rights reserved.
Fundamentals of the Analysis of Algorithm Efficiency
Analysis of algorithms
Fundamentals of the Analysis of Algorithm Efficiency
Presentation transcript:

Introduction to Algorithms Rabie A. Ramadan rabie@rabieramadan.org http://www. rabieramadan.org 3 Some of the sides are exported from different sources to clarify the topic

Time efficiency of nonrecursive algorithms General Plan for Analysis Decide on parameter n indicating input size Identify algorithm’s basic operation Determine worst, average, and best cases for input of size n Set up a sum for the number of times the basic operation is executed Simplify the sum using standard formulas and rules.

Example 1: The Largest Element T(n) = 1in-1 (1) = n-1 = (n) comparisons

Example 2: Element uniqueness problem T(n) = 0in-2 (i+1jn-1 (1)) = 0in-2 (n-i+1) = = ( ) comparisons

Example 3: Matrix multiplication T(n) = = ( ) multiplications Ignored addition for simplicity

Plan for Analysis of Recursive Algorithms Decide on a parameter indicating an input’s size. Identify the algorithm’s basic operation. Check whether the number of times the basic op. is executed may vary on different inputs of the same size. (If it may, the worst, average, and best cases must be investigated separately.) Set up a recurrence relation with an appropriate initial condition expressing the number of times the basic op. is executed. Solve the recurrence (or, at the very least, establish its solution’s order of growth) by backward substitutions or another method.

Example 1 : Factorial: Recursive Algorithm The stopping condition is n=0 A repetitive algorithm uses recursion whenever the algorithm appears within the definition itself.

Example 1: Recursive evaluation of n! Definition: n ! = 1  2  … (n-1)  n for n ≥ 1 and 0! = 1 Recursive definition of n!: F(n) = F(n-1)  n for n ≥ 1 and F(0) = 1 Size: Basic operation: Recurrence relation: Note the difference between the two recurrences. Students often confuse these! F(n) = F(n-1) n F(0) = 1 for the values of n! ------------ M(n) =M(n-1) + 1 M(0) = 0 for the number of multiplications made by this algorithm n multiplication M(n) = M(n-1) (for F(n-1) ) + 1 (for the n * F(n-1)) M(0) = 0

Solving the recurrence for M(n) M(n) = M(n-1) + 1, M(0) = 0 (no multiplication when n=0) M(n) = M(n-1) + 1 = (M(n-2) + 1) + 1 = M(n-2) + 2 = (M(n-3) + 1) + 2 = M(n-3) + 3 … = M(n-i) + i = M(0) + n = n The method is called backward substitution.

Example 2: The Tower of Hanoi Puzzle Towers of Hanoi (aka Tower of Hanoi) is a mathematical puzzle invented by a French Mathematician Edouard Lucas in 1983. Initially the game has few discs arranged in the increasing order of size in one of the tower. The number of discs can vary, but there are only three towers. The goal is to transfer the discs from one tower another tower. However you can move only one disk at a time and you can never place a bigger disc over a smaller disk. It is also understood that you can only take the top most disc from any given tower.

Example 2: The Tower of Hanoi Puzzle Recurrence for number of moves: M(n) = 2M(n-1) + 1

Move Sequence for d = 3 1 2 3 4 5 6 7 7 moves , Right !!!

The Tower of Hanoi Puzzle Here's how to find the number of moves needed to transfer larger numbers of disks from post A to post C, when M = the number of moves needed to transfer n-1 disks from post A to post C: for 1 disk it takes 1 move to transfer 1 disk from post A to post C; for 2 disks, it will take 3 moves: 2M + 1 = 2(1) + 1 = 3 for 3 disks, it will take 7 moves: 2M + 1 = 2(3) + 1 = 7 for 4 disks, it will take 15 moves: 2M + 1 = 2(7) + 1 = 15 for 5 disks, it will take 31 moves: 2M + 1 = 2(15) + 1 = 31 for 6 disks... ? 63

Explicit Pattern Number of Disks Number of Moves 1 1 2 3 3 7 4 15 5 31 1 1 2 3 3 7 4 15 5 31 6 63

Powers of two help reveal the pattern: Number of Disks (n) Number of Moves 1 21 - 1 = 2 - 1 = 1 2 22 - 1 = 4 - 1 = 3 3 23 - 1 = 8 - 1 = 7 4 24 - 1 = 16 - 1 = 15 5 25 - 1 = 32 - 1 = 31 6 26 - 1 = 64 - 1 = 63

Fascinating fact So the formula for finding the number of steps it takes to transfer n disks from post A to post C is: 2 n - 1

Solving recurrence for number of moves M(n) = 2M(n-1) + 1, M(1) = 1 M(n) = 2M(n-1) + 1 = 2(2M(n-2) + 1) + 1 = 2^2*M(n-2) + 2^1 + 2^0 = 2^2*(2M(n-3) + 1) + 2^1 + 2^0 = 2^3*M(n-3) + 2^2 + 2^1 + 2^0 = … = 2^(n-1)*M(1) + 2^(n-2) + … + 2^1 + 2^0 = 2^(n-1) + 2^(n-2) + … + 2^1 + 2^0 = 2^n - 1

What Is the Important of Fibonacci Sequence? The Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, … The Fibonacci recurrence: F(n) = F(n-1) + F(n-2) F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) or F(n) - F(n-1) - F(n-2) = 0 General 2nd order linear homogeneous recurrence with constant coefficients: aX(n) + bX(n-1) + cX(n-2) = 0

Chapter 3 Brute Force Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

Brute Force A straightforward approach, usually based directly on the problem’s statement and definitions of the concepts involved Examples: Computing an (a > 0, n a nonnegative integer)= a*a*….*a Computing n! Multiplying two matrices Searching for a key of a given value in a list

Brute-Force Sorting Algorithm Selection Sort Scan the array to find its smallest element and swap it with the first element. Then, starting with the second element, scan the elements to the right of it to find the smallest among them and swap it with the second elements. Generally, on pass i (0  i  n-2), find the smallest element in A[i..n-1] and swap it with A[i]: A[0]  . . .  A[i-1] | A[i], . . . , A[min], . . ., A[n-1] in their final positions Example: 7 3 2 5

Analysis of Selection Sort Time efficiency: Space efficiency: Stability: Θ(n^2) Θ(1), so in place yes

Brute Force - Bubble Sort Another brute force application to the sorting problem is to compare adjacent elements of the list. and exchange them if they are out of order. By doing it repeatedly, we end up “Bubbling up” the largest element to the last position on the list The next pass bubbles up the second largest element, and so on until, after n-1 passes, the list is sorted.

Brute Force - Bubble Sort Algorithm BubbleSort (A[0…n-1]) for i ← 0 to n-2 do for j ← 0 to n-2-i do if A[j]<A[j+1] swap A[j] and A[j+1] The number of times it is executed T(n) depends only on the array’s size and is given by the following sum:

Brute-Force String Matching pattern: a string of m characters to search for text: a (longer) string of n characters to search in problem: find a substring in the text that matches the pattern Brute-force algorithm Step 1 Align pattern at beginning of text Step 2 Moving from left to right, compare each character of pattern to the corresponding character in text until all characters are found to match (successful search); or a mismatch is detected Step 3 While pattern is not found and the text is not yet exhausted, realign pattern one position to the right and repeat Step 2

Examples of Brute-Force String Matching Pattern: 001011 Text: 10010101101001100101111010 Pattern: happy Text: It is never too late to have a happy childhood.

Pseudocode and Efficiency Time efficiency: Θ(mn) comparisons (in the worst case)

Brute-Force Polynomial Evaluation Problem: Find the value of polynomial p(x) = anxn + an-1xn-1 +… + a1x1 + a0 at a point x = x0 Brute-force algorithm Efficiency: p  0.0 for i  n downto 0 do power  1 for j  1 to i do //compute xi power  power  x p  p + a[i]  power return p Θ(n^2) multiplications

Polynomial Evaluation: Improvement We can do better by evaluating from right to left: Better brute-force algorithm Efficiency: Horner’s Rule is another linear time method. p  a[0] power  1 for i  1 to n do power  power  x p  p + a[i]  power return p Θ(n) multiplications

Closest-Pair Problem Find the two closest points in a set of n points (in the two-dimensional Cartesian plane). Brute-force algorithm Compute the distance between every pair of distinct points and return the indexes of the points for which the distance is the smallest. Draw example.

Closest-Pair Brute-Force Algorithm (cont.) The basic operation of the algorithm is computing the Euclidean distance between two points. The square root is a complex operation who’s result is often irrational, therefore the results can be found only approximately. Computing such operations are not trivial. One can avoid computing square roots by comparing distance squares instead. Efficiency: How to make it faster? Θ(n^2) multiplications Using divide-and-conquer!

Brute-Force Strengths and Weaknesses wide applicability simplicity yields reasonable algorithms for some important problems (e.g., matrix multiplication, sorting, searching, string matching) Weaknesses rarely yields efficient algorithms some brute-force algorithms are unacceptably slow not as constructive as some other design techniques

Exhaustive Search A brute force solution to a problem involving search for an element with a special property, usually among combinatorial objects such as permutations, combinations, or subsets of a set. Method: generate a list of all potential solutions to the problem in a systematic manner evaluate potential solutions one by one, disqualifying infeasible ones and, for an optimization problem, keeping track of the best one found so far when search ends, announce the solution(s) found

Example 1: Traveling Salesman Problem Given n cities with known distances between each pair, find the shortest tour that passes through all the cities exactly once before returning to the starting city Alternatively: Find shortest Hamiltonian circuit in a weighted connected graph Example: a b c d 8 2 7 5 3 4 How do we represent a solution (Hamiltonian circuit)?

TSP by Exhaustive Search Tour Cost a→b→c→d→a 2+3+7+5 = 17 a→b→d→c→a 2+4+7+8 = 21 a→c→b→d→a 8+3+4+5 = 20 a→c→d→b→a 8+7+4+2 = 21 a→d→b→c→a 5+4+3+8 = 20 a→d→c→b→a 5+7+3+2 = 17 Efficiency: a b c d 8 2 7 5 3 4 Θ((n-1)!) Chapter 5 discusses how to generate permutations fast.

Example 2: Knapsack Problem Given n items: weights: w1 w2 … wn values: v1 v2 … vn a knapsack of capacity W Find most valuable subset of the items that fit into the knapsack Example: Knapsack capacity W=16 item weight value 2 $20 5 $30 10 $50 5 $10

Knapsack Problem by Exhaustive Search Subset Total weight Total value {1} 2 $20 {2} 5 $30 {3} 10 $50 {4} 5 $10 {1,2} 7 $50 {1,3} 12 $70 {1,4} 7 $30 {2,3} 15 $80 {2,4} 10 $40 {3,4} 15 $60 {1,2,3} 17 not feasible {1,2,4} 12 $60 {1,3,4} 17 not feasible {2,3,4} 20 not feasible {1,2,3,4} 22 not feasible Efficiency: Θ(2^n) Each subset can be represented by a binary string (bit vector, Ch 5).

Example 3: The Assignment Problem There are n people who need to be assigned to n jobs, one person per job. The cost of assigning person i to job j is C[i,j]. Find an assignment that minimizes the total cost. Job 1 Job 2 Job 3 Job 4 Person 1 9 2 7 8 Person 2 6 4 3 7 Person 3 5 8 1 8 Person 4 7 6 9 4 Algorithmic Plan: Generate all legitimate assignments, compute their costs, and select the cheapest one. How many assignments are there? n!

Assignment Problem by Exhaustive Search 9 2 7 8 6 4 3 7 5 8 1 8 7 6 9 4 Assignment (col.#s) Total Cost 1, 2, 3, 4 9+4+1+4=18 1, 2, 4, 3 9+4+8+9=30 1, 3, 2, 4 9+3+8+4=24 1, 3, 4, 2 9+3+8+6=26 1, 4, 2, 3 9+7+8+9=33 1, 4, 3, 2 9+7+1+6=23 etc. (For this particular instance, the optimal assignment can be found by exploiting the specific features of the number given. It is: ) 2,1,3,4

Final Comments on Exhaustive Search Exhaustive-search algorithms run in a realistic amount of time only on very small instances In some cases, there are much better alternatives! Euler circuits shortest paths assignment problem In many cases, exhaustive search or its variation is the only known way to get exact solution The Hungarian method runs in O(n^3) time.