ch03.0_Brute Force and Exhaustive Search.pdf
Document Details
Uploaded by PlayfulErbium
UKM
Tags
Full Transcript
Algorithms Analysis and Design Chapter 3: Brute Force and Exhaustive Search A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 1 Brute Force A strai...
Algorithms Analysis and Design Chapter 3: Brute Force and Exhaustive Search A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 1 Brute Force A straightforward approach, usually based directly on the problem’s statement and definitions of the concepts involved Examples: 1. Computing an (a ≠ 0, n a nonnegative integer) By the definition of exponentiation, 𝑎𝑛=𝑎∗…∗𝑎(𝑛𝑡𝑖𝑚𝑒𝑠)= This suggests simply computing 𝑎𝑛by multiplying 1 by 𝑎𝑛times 1. Computing n! 2. Multiplying two matrices 3. Searching for a key of a given value in a list A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 2 Brute-Force Sorting Algorithm Problem of sorting: given a list of 𝑛 orderable items (e.g., numbers, characters from some alphabet, character strings), rearrange them in nondecreasing order. 3 Selection Sort Scan the list 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 the ith pass through the list, (0 i n-2), the algorithm searches for the smallest item among the last n-i elements and swap it with Ai find the smallest element in A[i..n-1] and swap it with A[i]: After n-1 passes, the list is sorted. 4 Selection Sort Algorithm A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 5 Analysis of Selection Sort The input size is given by the number of elements n The basic operation is the key comparison A[j ] < A[min]. The number of times it is executed depends only on the array size Time efficiency: Θ(𝑛2) algorithm on all inputs. Space efficiency: O(1) , for temp variable for swapping Stability: No A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 6 Selection Sort Example Each line corresponds to one iteration of the algorithm, i.e., a pass through the list’s tail to the right of the vertical bar; an element in bold indicates the smallest element found. Elements to the left of the vertical bar are in their final positions and are not considered in this and subsequent iterations. A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 7 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 𝑛−1 passes the list is sorted. A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 9 Bubbling Sort Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 77 42 35 12 101 5 "Bubbling Up" the Largest Element Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 42Swap42 77 77 35 12 101 5 "Bubbling Up" the Largest Element Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 42 35Swap35 77 77 12 101 5 "Bubbling Up" the Largest Element Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 42 35 12Swap12 77 77 101 5 "Bubbling Up" the Largest Element Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 42 35 12 77 101 5 No need to swap "Bubbling Up" the Largest Element Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 42 35 12 77 5 Swap101 101 5 "Bubbling Up" the Largest Element Traverse a collection of elements Move from the front to the end “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 42 35 12 77 5 101 Largest value correctly placed Items of Interest Notice that only the largest value is correctly placed All other values are still out of order So we need to repeat this process 1 2 3 4 5 6 42 35 12 77 5 101 Largest value correctly placed Repeat “Bubble Up” How Many Times? If we have N elements… And if each time we bubble an element, we place it in its correct location… Then we repeat the “bubble up” process N – 1 times. This guarantees we’ll correctly place all N elements. “Bubbling” All the Elements 1 2 3 4 5 6 42 35 12 77 5 101 1 2 3 4 5 6 35 12 42 5 77 101 1 2 3 4 5 6 N-1 12 35 5 42 77 101 1 2 3 4 5 6 12 5 35 42 77 101 1 2 3 4 5 6 5 12 35 42 77 101 Bubble Sort Analysis A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 20 Bubble Sort Analysis The number of key comparisons for the bubble-sort is the same for all arrays of size 𝑛; it is obtained by a sum that is almost identical to the sum for selection sort The number of key swaps, however, depends on the input. In the worst case of decreasing arrays, it is the same as the number of key comparisons: A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 21 Brute-Force Sequential Search Compares successive elements of a given list with a given search key until either a match is encountered (successful search) or the list is exhausted without finding a match (unsuccessful search). simple extra trick: eliminate the end of list check altogether A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 22 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 A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 23 Examples of Brute-Force String Matching Pattern: 001011 Text: 10010101101001100101111010 Pattern: happy Text: It is never too late to have a happy childhood. A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 24 Pseudocode and Efficiency Efficiency: O(n*m) in the worst case A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 25 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 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 Efficiency: O(n^2) A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 30 Polynomial Evaluation: Improvement We can do better by evaluating from right to left: Better brute-force algorithm p a power 1 for i 1 to n do power power x p p + a[i] power return p Efficiency: O(n) A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 31 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. A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 32 Closest-Pair Brute-Force Algorithm (cont.) Optimization Techniques Early Termination: If you find a pair of points with a distance of 0, you can immediately return those points as the closest pair. This can save time in cases where there are duplicate points in the dataset. Data Structure Optimization: Use efficient data structures to store and access point coordinates. For example, using a hash table or a spatial index can potentially improve lookup times, but the overhead might outweigh the benefits for small datasets. Parallel Processing: If you have access to multiple cores or processors, you can Efficiency: O(n^2). distribute the pairwise distance calculations across them. This can significantly speed up the process for large datasets. How to make it faster? A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 33 Brute-Force Strengths and Weaknesses Strengths 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 A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 34 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. Many such problems are optimization problems 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 A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 35 Applications Travelling person selling products Robots drilling holes Logistic Art Development and testing of optimization algorithms Traveling Salesman Problem (TSP) 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: 2 a b 5 3 8 4 c 7 d A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 37 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 2 a b More tours? 5 3 8 4 Less tours? c 7 d Efficiency: O(n!) A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 38 Example Example Cost of optimal tour = 11 Knapsack Problem Given n items: weights: w1 w2 … wn values: v 1 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 1 2 $20 2 5 $30 3 10 $50 4 5 $10 A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 41 Knapsack Problem by Exhaustive Search Subset Total weight Total value {1} 2 $20 {2} 5 $30 item weight value {3} 10 $50 1 2 $20 {4} 5 $10 2 5 $30 {1,2} 7 $50 3 10 $50 {1,3} 12 $70 4 5 $10 {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: A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 42 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 5 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? A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 43 Assignment Problem by Exhaustive Search 9 2 7 8 6 4 3 7 the problem as a cost matrix C= 5 8 1 8 generating all the permutations of 7 6 9 4 integers 1, 2, 3, 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. etc. Number of permutations for the general case of this problem is n! exhaustive search is impractical for all but very small instances of the problem. A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 44 Final Comments on Exhaustive Search Exhaustive-search algorithms run in a realistic amount of time only on very small instances In many cases, exhaustive search or its variation is the only known way to get exact solution A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. 45