SlideShare a Scribd company logo
1 of 9
Download to read offline
Computer Science 385
                                     Analysis of Algorithms
                                     Siena College
                                     Spring 2011


                 Topic Notes: Brute-Force Algorithms

Our ļ¬rst category of algorithms are called brute-force algorithms.
Levitin deļ¬nes brute force as a straightforward approach, usually based directly on the problem
statement and deļ¬nitions of the concepts involved.
We have already seen a few examples:

   ā€¢ consecutive integer checking approach for ļ¬nding a GCD

   ā€¢ matrix-matrix multiplication

Another is the computation of an by multiplying by a n times.
Brute-force algorithms are not usually clever or especially efļ¬cient, but they are worth considering
for several reasons:

   ā€¢ The approach applies to a wide variety of problems.

   ā€¢ Some brute-force algorithms are quite good in practice.

   ā€¢ It may be more trouble than itā€™s worth to design and implement a more clever or efļ¬cient
     algorithm over using a straightforward brute-force approach.



Brute-Force Sorting
One problem we will return to over and over is that of sorting. We will ļ¬rst consider some brute-
force approaches.
We will usually look at sorting arrays of integer values, but the algorithms can be used for other
comparable data types.

Bubble Sort
We begin with a very intuitive sort. We just go through our array, looking at pairs of values and
swapping them if they are out of order.
It takes n āˆ’ 1 ā€œbubble-upsā€, each of which can stop sooner than the last, since we know we bubble
up one more value to its correct position in each iteration. Hence the name bubble sort.
CS 385                                Analysis of Algorithms                          Spring 2011



bubble_sort(A[0..n-1]) {
  for (i = 0 to n-2)
    for (j=0 to n-2-i)
      if (A[j+1] < A[j]) swap A[j] and A[j+1]
}

The size parameter is n, the size of the input array.
The basic operation is either the comparison or the swap inside the innermost loop. The comparison
happens every time, while the swap only happens when necessary to reorder a pair of adjacent
elements. Remember that a swap involves three assignments, which would be more expensive
than the individual comparisons.
The best, average, and worst case for the number of comparisons is all the same. But for swaps,
it differs. Best case, the array is already sorted and we need not make any swaps. Worst case,
every comparison requires a swap. For an average case, we would need more information about
the likelihood of a swap being needed to do any exact analysis.
So we proceed by counting comparisons, and the summation will also give us a the worst case for
the number of swaps.


                                           nāˆ’2 nāˆ’2āˆ’i
                                 C(n) =                 1
                                           i=0    j=0
                                           nāˆ’2
                                       =         [(n āˆ’ 2 āˆ’ i) āˆ’ 0 + 1]
                                           i=0
                                           nāˆ’2
                                       =         (n āˆ’ 1 āˆ’ i)
                                           i=0
                                           (n āˆ’ 1)n
                                       =            āˆˆ Ī˜(n2 ).
                                              2

So we do Ī˜(n2 ) comparisons. We swap, potentially, after each one of these, a worse case behavior
of Ī˜(n2 ) swaps.

Selection Sort
A simple improvement on the bubble sort is based on the observation that one pass of the bubble
sort gets us closer to the answer by moving the largest unsorted element into its ļ¬nal position.
Other elements are moved ā€œcloserā€ to their ļ¬nal position, but all we can really say for sure after a
single pass is that we have positioned one more element.
So why bother with all of those intermediate swaps? We can just search through the unsorted part
of the array, remembering the index of (and hence, the value of) the largest element weā€™ve seen so
far, and when we get to the end, we swap the element in the last position with the largest element
we found. This is the selection sort.

                                                    2
CS 385                               Analysis of Algorithms                           Spring 2011



selection_sort(A[0..n-1]) {
  for (i = 0 to n-2)
    min = i
    for (j=i+1 to n-1)
      if (A[j] < A[min]) min = j;
    swap A[i] and A[min]
}

The number of comparisons is our basic operation here.


                                          nāˆ’2 nāˆ’2
                                C(n) =                1
                                          i=0 j=i+1
                                          nāˆ’2
                                      =         [(n āˆ’ 1) āˆ’ (i + 1) + 1]
                                          i=0
                                          nāˆ’2
                                      =         (n āˆ’ 1 āˆ’ i)
                                          i=0
                                        (n āˆ’ 1)n
                                      =          āˆˆ Ī˜(n2 ).
                                           2

Here, we do the same number of comparisons, but at most n āˆ’ 1 = Ī˜(n) swaps.


Brute-Force String Match
This problem involves searching for a pattern (substring) in a string of text.
The basic procedure:

   1. Align the pattern at beginning of the text

   2. Moving from left to right, compare each character of the pattern to the corresponding char-
      acter in the text until

         ā€¢ all characters are found to match (successful search); or
         ā€¢ a mismatch is detected

   3. While pattern is not found and the text is not yet exhausted, realign the pattern one position
      to the right and repeat Step 2

The result is either the index in the text of the ļ¬rst occurrence of the pattern, or indices of all
occurrences. We will look only for the ļ¬rst.
Written in pseudocode, our brute-force string match:

                                                    3
CS 385                               Analysis of Algorithms                            Spring 2011



brute_force_string_match(T[0..n-1], P[0..m-1]) {
  for (i-0 to n-m)
    j=0
    while (j<m) and P[j] == T[i+j]
      j++
    if j==m return i
  return -1
}

The sizes of the input strings, m for the pattern and n for the text, are the problem size parameters
and the basic operation is the element to element comparisons.
We have signiļ¬cant differences among the best, average, and worst cases. Best case, we ļ¬nd the
pattern at the start of the text and we need only m comparisons: Ī˜(m). In the worst case, we
encounter ā€œnear missesā€ at each starting location in the text, requiring about n searches of size m,
resulting in Ī˜(nm). On average, however, most non-matches are likely to be detected quickly: in
the ļ¬rst element or two, leading to an average case behavior of Ī˜(n).
We will consider improvements for string matching later in the semester.


Closest Pairs
Computational geometry is a rich area for the study of algorithms. Our next problem comes from
that ļ¬eld.
The problem: Find the two closest points in a set of n points (in the two-dimensional Cartesian
plane).
Brute-force algorithm: Compute the Euclidean distance between every pair of distinct points and
return the indices of the points for which the distance is the smallest.

brute_force_closest_points(a set of n points, P) {
  dmin = infinity
  for (i=1 to n-1)
    for (j=i+1 to n)
      d = sqrt(P[i].x - P[j].x)Ė†2 + (P[i].y - P[j].y)Ė†2))
      if (d < dmin)
        dmin = d
        index1 = i
        index2 = j
  return index1, index2
}

The problem size is deļ¬ned by the number of points, n. The basic operation is the computation of
the distance between each pair of points. It needs to be computed for each pair of points, so the
best, average, and worst cases are the same.

                                                 4
CS 385                                     Analysis of Algorithms                      Spring 2011



Before we continue, however, note that there is a way to improve the efļ¬ciency of this algorithm
signiļ¬cantly. Computing square roots is an expensive operation. But if we think about it a bit,
itā€™s also completely unnecessary here. Finding the minimum among a collection of square roots is
exactly the same as ļ¬nding the minimum among the original numbers. So it can be removed. This
leaves us with the squaring of numbers are our basic operation.
The number of squaring operations can be computed:


                           nāˆ’1     n
                  C(n) =               2
                           i=1 j=i+1
                             nāˆ’1
                        =2         (n āˆ’ i)
                             i=1
                        = 2[(n āˆ’ 1) + (n āˆ’ 2) + Ā· Ā· Ā· + 1] = 2(n āˆ’ 1)n āˆˆ Ī˜(n2 ).



Convex Hulls
Staying in the realm of computational geometry we consider the convex-hull problem.
The convex hull of a set of points in the plane is the smallest convex polygon that contains them
all.
So given a set of points, how can we ļ¬nd the convex hull? First, we should ļ¬nd the extreme points
ā€“ those points in our set that lie ā€œon the fringesā€ which will be the vertices of the polygon formed
by the points in the convex hull. Second, we need to know in what order to connect them to form
the convex polygon.
Our brute-force approach is anything but obvious. Our solution will depend on the observation
that any line segment connecting two adjacent points on the convex hull will have all other points
in the set on the same side of the straight line between its endpoints.
Recall from your high school math that the straight line through two points (x1 , y1 ) and (x2 , y2 )
can be deļ¬ned by


                     ax + by = c, a = y2 āˆ’ y1 , b = x1 āˆ’ x2 , c = x1 y2 āˆ’ y1 x2 .

We can tell which side of this line any point is by computing ax + by and seeing if it is greater than
or less than c. All points where ax + by < c are on one side of the line, those where ax + by > c
are on the other. Points on the line will satisfy ax + by = c, of course.
So our algorithm will need to consider each pair of points, and see if all other points lie on the
same side. If so, the points are part of the convex hull. If not, they are not.

brute_force_convex_hull(a set of n points, P) {

                                                     5
CS 385                                 Analysis of Algorithms                           Spring 2011



    create empty set of line segments L
    for (each point p1 in P)
      for (each point p2 in P after p1)
        a = p2.y - p1.y; b = p1.x - p2.x;
        c = p1.x*p2.y - p1.y*p2.x
        foundProblem = false
        for (each point p3 in P (not p1 or p2))
          check = a*p3.x + b*p3.y - c
          if (check does not match others)
            foundProblem=true
            break
        if (!foundProblem) add segment p1,p2 to L
    extract and return list of points from L
}

See Example:
Ėœjteresco/shared/cs385/examples/BruteForceConvexHull
For this problem, the size is determined by the number of input points. Its basic operation is the
compute of the check in the innermost loop (probably multiplications).
For best, average, and worst case behavior, the differences would arise in how quickly we could
determine that a given segment is not part of the convex polygon for those that are not. Best case,
we would quickly ļ¬nd evidence for those which are not. Worst case, we need to look through most
of the points before making a determination.
Considering the worst case, we can see that the number of basic operations will be Ī˜(n3 ).


Exhaustive Search
An exhaustive search is 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.
The typical approach involves:

    1. Generation of a list of all potential solutions to the problem in a systematic manner (e.g., our
       permutations from the ļ¬rst problem set ā€“ we will see others).

    2. Evaluation of the potential solutions one by one, disqualifying infeasible ones and, for an
       optimization problem, keeping track of the best one found so far.

    3. Announcing the solution when the search ends.

We will look brieļ¬‚y at a few examples of problems that can be solved with exhaustive search.


                                                   6
CS 385                                  Analysis of Algorithms                               Spring 2011



Traveling Salesman
The traveling salesman problem (TSP) asks us, given n cities with known distances between each
pair, ļ¬nd the shortest tour that passes through all the cities exactly once before returning to the
starting city.
Solutions to this kind of problem have important practical applications (delivery services, census
takers, etc.)
An alternative statement of the problem is to ļ¬nd the shortest Hamiltonian circuit in a weighted,
connected graph. A Hamiltonian circuit is a cycle that passes through all of the vertices of the
graph exactly once.
If we think about it a bit, we can see that it does not matter where our tour begins and ends ā€“ itā€™s a
cycle ā€“ so we can choose any city/vertex as the starting point and consider all permutation of the
other n āˆ’ 1 vertices.
So an exhaustive search would allow us to consider all (n āˆ’ 1)! permutations, compute the cost
(total distance traveled) for each, returning the lowest cost circuit found.
The text has a small example.

Knapsack Problem
Another well-known problem is the knapsack problem.
Given n items with weights w1 , w2 , ..., wn and values v1 , v2 , ..., vn , what is the most vaulable subset
of items that can ļ¬t into a knapsack that can hold a total weight W .
The exhaustive search here involves considering all possible subsets of items and ļ¬nding the subset
whose total weight is no more than W with the highest value.
For n items, this means we have to generate 2n subsets, giving us that as a lower bound on our cost
of ā„¦(2n ).
An example of this problem with a knapsack capacity of 16:

                                          item   weight     value
                                            1      2         20
                                            2      5         30
                                            3     10         50
                                            4      5         10

All possible subsets (not including the empty set, which would be the answer only if all items were
too heavy to be in the knapsack even alone):




                                                     7
CS 385                                Analysis of Algorithms                            Spring 2011


                                     subset    weight      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       too heavy
                                    {1,2,4}     12           60
                                    {1,3,4}     17       too heavy
                                    {2,3,4}     20       too heavy
                                   {1,2,3,4}    22       too heavy

So the winner is {2,3} with a total weight of 15 and a total value of 80.

Assignment Problem
Our ļ¬nal exhaustive search example is the assignment problem. It may be stated as the assignment
of n jobs among n people, one job per person, where the cost of assigning person i to job i is given
by C[i, j], and we wish to minimize the total cost across all possible assignments.
For example, consider this cost matrix:

                                          Job 0   Job 1 Job 2 Job 3
                              Person 0      9       2     7     8
                              Person 1      6       4     3     7
                              Person 2      5       8     1     8
                              Person 3      7       6     9     4

Our exhaustive search here involves the generation of all possible assignments, computing the total
cost of each, and selection of the lowest cost.
How many assignments as possible? Well, we can assign the ļ¬rst person any of n jobs. Then, there
are n āˆ’ 1 to choose for the second person, n āˆ’ 2 for the third, and so on, until there is just one
remaining choice for the last person: a total of n!.
We can list the solutions by generating all permutations of the numbers 1, 2, ..., n (sound familiar?),
and treating the number in each position as the job to assign to the person at that position.

Exhaustive Search Wrapup

   ā€¢ Exhaustive-search algorithms run in a realistic amount of time only on very small instances.

                                                  8
CS 385                           Analysis of Algorithms                        Spring 2011



  ā€¢ Sometimes, much better approaches exist (and we will see some of those soon).

  ā€¢ But sometimes, an exhaustive search is the only known way to be guaranteed an exact solu-
    tion.




                                             9

More Related Content

What's hot

PaperNo14-Habibi-IJMA-n-Tuples and Chaoticity
PaperNo14-Habibi-IJMA-n-Tuples and ChaoticityPaperNo14-Habibi-IJMA-n-Tuples and Chaoticity
PaperNo14-Habibi-IJMA-n-Tuples and ChaoticityMezban Habibi
Ā 
Time Series Analysis
Time Series AnalysisTime Series Analysis
Time Series AnalysisAmit Ghosh
Ā 
Generalization of Tensor Factorization and Applications
Generalization of Tensor Factorization and ApplicationsGeneralization of Tensor Factorization and Applications
Generalization of Tensor Factorization and ApplicationsKohei Hayashi
Ā 
Nonnegative Matrix Factorization
Nonnegative Matrix FactorizationNonnegative Matrix Factorization
Nonnegative Matrix FactorizationTatsuya Yokota
Ā 
Tensor Decomposition and its Applications
Tensor Decomposition and its ApplicationsTensor Decomposition and its Applications
Tensor Decomposition and its ApplicationsKeisuke OTAKI
Ā 
On estimating the integrated co volatility using
On estimating the integrated co volatility usingOn estimating the integrated co volatility using
On estimating the integrated co volatility usingkkislas
Ā 
08 decrease and conquer spring 15
08 decrease and conquer spring 1508 decrease and conquer spring 15
08 decrease and conquer spring 15Hira Gul
Ā 
Doering Savov
Doering SavovDoering Savov
Doering Savovgh
Ā 
Two parameter entropy of uncertain variable
Two parameter entropy of uncertain variableTwo parameter entropy of uncertain variable
Two parameter entropy of uncertain variableSurender Singh
Ā 
Introduction to FEM
Introduction to FEMIntroduction to FEM
Introduction to FEMmezkurra
Ā 
Polyadic integer numbers and finite (m,n) fields
Polyadic integer numbers and finite (m,n) fieldsPolyadic integer numbers and finite (m,n) fields
Polyadic integer numbers and finite (m,n) fieldsSteven Duplij (Stepan Douplii)
Ā 
Nonlinear Stochastic Programming by the Monte-Carlo method
Nonlinear Stochastic Programming by the Monte-Carlo methodNonlinear Stochastic Programming by the Monte-Carlo method
Nonlinear Stochastic Programming by the Monte-Carlo methodSSA KPI
Ā 
A brief introduction to Hartree-Fock and TDDFT
A brief introduction to Hartree-Fock and TDDFTA brief introduction to Hartree-Fock and TDDFT
A brief introduction to Hartree-Fock and TDDFTJiahao Chen
Ā 
Bachelor_Defense
Bachelor_DefenseBachelor_Defense
Bachelor_DefenseTeja Turk
Ā 
PaperNo17-HabibiMasoudiSafari-IJCMA
PaperNo17-HabibiMasoudiSafari-IJCMAPaperNo17-HabibiMasoudiSafari-IJCMA
PaperNo17-HabibiMasoudiSafari-IJCMAMezban Habibi
Ā 
Solution of linear and nonlinear partial differential equations using mixture...
Solution of linear and nonlinear partial differential equations using mixture...Solution of linear and nonlinear partial differential equations using mixture...
Solution of linear and nonlinear partial differential equations using mixture...Alexander Decker
Ā 

What's hot (20)

Am26242246
Am26242246Am26242246
Am26242246
Ā 
PaperNo14-Habibi-IJMA-n-Tuples and Chaoticity
PaperNo14-Habibi-IJMA-n-Tuples and ChaoticityPaperNo14-Habibi-IJMA-n-Tuples and Chaoticity
PaperNo14-Habibi-IJMA-n-Tuples and Chaoticity
Ā 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Ā 
Time Series Analysis
Time Series AnalysisTime Series Analysis
Time Series Analysis
Ā 
Lecture5
Lecture5Lecture5
Lecture5
Ā 
Generalization of Tensor Factorization and Applications
Generalization of Tensor Factorization and ApplicationsGeneralization of Tensor Factorization and Applications
Generalization of Tensor Factorization and Applications
Ā 
paper
paperpaper
paper
Ā 
Nonnegative Matrix Factorization
Nonnegative Matrix FactorizationNonnegative Matrix Factorization
Nonnegative Matrix Factorization
Ā 
Tensor Decomposition and its Applications
Tensor Decomposition and its ApplicationsTensor Decomposition and its Applications
Tensor Decomposition and its Applications
Ā 
On estimating the integrated co volatility using
On estimating the integrated co volatility usingOn estimating the integrated co volatility using
On estimating the integrated co volatility using
Ā 
08 decrease and conquer spring 15
08 decrease and conquer spring 1508 decrease and conquer spring 15
08 decrease and conquer spring 15
Ā 
Doering Savov
Doering SavovDoering Savov
Doering Savov
Ā 
Two parameter entropy of uncertain variable
Two parameter entropy of uncertain variableTwo parameter entropy of uncertain variable
Two parameter entropy of uncertain variable
Ā 
Introduction to FEM
Introduction to FEMIntroduction to FEM
Introduction to FEM
Ā 
Polyadic integer numbers and finite (m,n) fields
Polyadic integer numbers and finite (m,n) fieldsPolyadic integer numbers and finite (m,n) fields
Polyadic integer numbers and finite (m,n) fields
Ā 
Nonlinear Stochastic Programming by the Monte-Carlo method
Nonlinear Stochastic Programming by the Monte-Carlo methodNonlinear Stochastic Programming by the Monte-Carlo method
Nonlinear Stochastic Programming by the Monte-Carlo method
Ā 
A brief introduction to Hartree-Fock and TDDFT
A brief introduction to Hartree-Fock and TDDFTA brief introduction to Hartree-Fock and TDDFT
A brief introduction to Hartree-Fock and TDDFT
Ā 
Bachelor_Defense
Bachelor_DefenseBachelor_Defense
Bachelor_Defense
Ā 
PaperNo17-HabibiMasoudiSafari-IJCMA
PaperNo17-HabibiMasoudiSafari-IJCMAPaperNo17-HabibiMasoudiSafari-IJCMA
PaperNo17-HabibiMasoudiSafari-IJCMA
Ā 
Solution of linear and nonlinear partial differential equations using mixture...
Solution of linear and nonlinear partial differential equations using mixture...Solution of linear and nonlinear partial differential equations using mixture...
Solution of linear and nonlinear partial differential equations using mixture...
Ā 

Viewers also liked

Viewers also liked (6)

Slovenia2
Slovenia2Slovenia2
Slovenia2
Ā 
Turmoil In The Balkans
Turmoil In The BalkansTurmoil In The Balkans
Turmoil In The Balkans
Ā 
Female samurai presentation
Female samurai presentationFemale samurai presentation
Female samurai presentation
Ā 
13.6 pba mogolian and chinese girls
13.6 pba mogolian and chinese girls13.6 pba mogolian and chinese girls
13.6 pba mogolian and chinese girls
Ā 
The history of Slovenia tna
The history of Slovenia   tnaThe history of Slovenia   tna
The history of Slovenia tna
Ā 
Slovenia Presentation
Slovenia PresentationSlovenia Presentation
Slovenia Presentation
Ā 

Similar to CS 385 Analysis of Algorithms Brute-Force Algorithms

Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquerchidabdu
Ā 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquerchidabdu
Ā 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortzukun
Ā 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyappasami
Ā 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
Ā 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2Deepak John
Ā 
1_Asymptotic_Notation_pptx.pptx
1_Asymptotic_Notation_pptx.pptx1_Asymptotic_Notation_pptx.pptx
1_Asymptotic_Notation_pptx.pptxpallavidhade2
Ā 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithmspppepito86
Ā 
Cs1311lecture23wdl
Cs1311lecture23wdlCs1311lecture23wdl
Cs1311lecture23wdlMuhammad Wasif
Ā 
Introduction
IntroductionIntroduction
Introductionpilavare
Ā 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfAmayJaiswal4
Ā 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and AnalysisReetesh Gupta
Ā 
Skiena algorithm 2007 lecture02 asymptotic notation
Skiena algorithm 2007 lecture02 asymptotic notationSkiena algorithm 2007 lecture02 asymptotic notation
Skiena algorithm 2007 lecture02 asymptotic notationzukun
Ā 
Dr hasany 2467_16649_1_lec-2-zabist
Dr hasany 2467_16649_1_lec-2-zabistDr hasany 2467_16649_1_lec-2-zabist
Dr hasany 2467_16649_1_lec-2-zabistGatewayggg Testeru
Ā 
Algorithms - Rocksolid Tour 2013
Algorithms  - Rocksolid Tour 2013Algorithms  - Rocksolid Tour 2013
Algorithms - Rocksolid Tour 2013Gary Short
Ā 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsortschidabdu
Ā 

Similar to CS 385 Analysis of Algorithms Brute-Force Algorithms (20)

Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
Ā 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
Ā 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
Ā 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksort
Ā 
Ada notes
Ada notesAda notes
Ada notes
Ā 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
Ā 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
Ā 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2
Ā 
1_Asymptotic_Notation_pptx.pptx
1_Asymptotic_Notation_pptx.pptx1_Asymptotic_Notation_pptx.pptx
1_Asymptotic_Notation_pptx.pptx
Ā 
Slide2
Slide2Slide2
Slide2
Ā 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
Ā 
Cs1311lecture23wdl
Cs1311lecture23wdlCs1311lecture23wdl
Cs1311lecture23wdl
Ā 
Introduction
IntroductionIntroduction
Introduction
Ā 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdf
Ā 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and Analysis
Ā 
Skiena algorithm 2007 lecture02 asymptotic notation
Skiena algorithm 2007 lecture02 asymptotic notationSkiena algorithm 2007 lecture02 asymptotic notation
Skiena algorithm 2007 lecture02 asymptotic notation
Ā 
Brute force method
Brute force methodBrute force method
Brute force method
Ā 
Dr hasany 2467_16649_1_lec-2-zabist
Dr hasany 2467_16649_1_lec-2-zabistDr hasany 2467_16649_1_lec-2-zabist
Dr hasany 2467_16649_1_lec-2-zabist
Ā 
Algorithms - Rocksolid Tour 2013
Algorithms  - Rocksolid Tour 2013Algorithms  - Rocksolid Tour 2013
Algorithms - Rocksolid Tour 2013
Ā 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
Ā 

More from chidabdu

Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffmanchidabdu
Ā 
Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphschidabdu
Ā 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamicchidabdu
Ā 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashingchidabdu
Ā 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heapschidabdu
Ā 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bstchidabdu
Ā 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysischidabdu
Ā 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 introchidabdu
Ā 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitationschidabdu
Ā 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unitchidabdu
Ā 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organizationchidabdu
Ā 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1chidabdu
Ā 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11chidabdu
Ā 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10chidabdu
Ā 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9chidabdu
Ā 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8chidabdu
Ā 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7chidabdu
Ā 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6chidabdu
Ā 
Algorithm chapter 5
Algorithm chapter 5Algorithm chapter 5
Algorithm chapter 5chidabdu
Ā 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2chidabdu
Ā 

More from chidabdu (20)

Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
Ā 
Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphs
Ā 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
Ā 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
Ā 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
Ā 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bst
Ā 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
Ā 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 intro
Ā 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitations
Ā 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
Ā 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
Ā 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
Ā 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
Ā 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
Ā 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9
Ā 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8
Ā 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7
Ā 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
Ā 
Algorithm chapter 5
Algorithm chapter 5Algorithm chapter 5
Algorithm chapter 5
Ā 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
Ā 

Recently uploaded

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
Ā 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
Ā 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...gurkirankumar98700
Ā 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
Ā 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĆŗjo
Ā 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Ā 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
Ā 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
Ā 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
Ā 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
Ā 
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024BookNet Canada
Ā 
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...Alan Dix
Ā 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
Ā 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
Ā 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
Ā 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
Ā 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
Ā 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
Ā 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service šŸø 8923113531 šŸŽ° Avail...
Ā 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Ā 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Ā 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Ā 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Ā 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
Ā 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
Ā 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
Ā 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Ā 
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: Whatā€™s new for BISAC - Tech Forum 2024
Ā 
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Swan(sea) Song ā€“ personal research during my six years at Swansea ... and bey...
Ā 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
Ā 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
Ā 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Ā 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
Ā 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
Ā 

CS 385 Analysis of Algorithms Brute-Force Algorithms

  • 1. Computer Science 385 Analysis of Algorithms Siena College Spring 2011 Topic Notes: Brute-Force Algorithms Our ļ¬rst category of algorithms are called brute-force algorithms. Levitin deļ¬nes brute force as a straightforward approach, usually based directly on the problem statement and deļ¬nitions of the concepts involved. We have already seen a few examples: ā€¢ consecutive integer checking approach for ļ¬nding a GCD ā€¢ matrix-matrix multiplication Another is the computation of an by multiplying by a n times. Brute-force algorithms are not usually clever or especially efļ¬cient, but they are worth considering for several reasons: ā€¢ The approach applies to a wide variety of problems. ā€¢ Some brute-force algorithms are quite good in practice. ā€¢ It may be more trouble than itā€™s worth to design and implement a more clever or efļ¬cient algorithm over using a straightforward brute-force approach. Brute-Force Sorting One problem we will return to over and over is that of sorting. We will ļ¬rst consider some brute- force approaches. We will usually look at sorting arrays of integer values, but the algorithms can be used for other comparable data types. Bubble Sort We begin with a very intuitive sort. We just go through our array, looking at pairs of values and swapping them if they are out of order. It takes n āˆ’ 1 ā€œbubble-upsā€, each of which can stop sooner than the last, since we know we bubble up one more value to its correct position in each iteration. Hence the name bubble sort.
  • 2. CS 385 Analysis of Algorithms Spring 2011 bubble_sort(A[0..n-1]) { for (i = 0 to n-2) for (j=0 to n-2-i) if (A[j+1] < A[j]) swap A[j] and A[j+1] } The size parameter is n, the size of the input array. The basic operation is either the comparison or the swap inside the innermost loop. The comparison happens every time, while the swap only happens when necessary to reorder a pair of adjacent elements. Remember that a swap involves three assignments, which would be more expensive than the individual comparisons. The best, average, and worst case for the number of comparisons is all the same. But for swaps, it differs. Best case, the array is already sorted and we need not make any swaps. Worst case, every comparison requires a swap. For an average case, we would need more information about the likelihood of a swap being needed to do any exact analysis. So we proceed by counting comparisons, and the summation will also give us a the worst case for the number of swaps. nāˆ’2 nāˆ’2āˆ’i C(n) = 1 i=0 j=0 nāˆ’2 = [(n āˆ’ 2 āˆ’ i) āˆ’ 0 + 1] i=0 nāˆ’2 = (n āˆ’ 1 āˆ’ i) i=0 (n āˆ’ 1)n = āˆˆ Ī˜(n2 ). 2 So we do Ī˜(n2 ) comparisons. We swap, potentially, after each one of these, a worse case behavior of Ī˜(n2 ) swaps. Selection Sort A simple improvement on the bubble sort is based on the observation that one pass of the bubble sort gets us closer to the answer by moving the largest unsorted element into its ļ¬nal position. Other elements are moved ā€œcloserā€ to their ļ¬nal position, but all we can really say for sure after a single pass is that we have positioned one more element. So why bother with all of those intermediate swaps? We can just search through the unsorted part of the array, remembering the index of (and hence, the value of) the largest element weā€™ve seen so far, and when we get to the end, we swap the element in the last position with the largest element we found. This is the selection sort. 2
  • 3. CS 385 Analysis of Algorithms Spring 2011 selection_sort(A[0..n-1]) { for (i = 0 to n-2) min = i for (j=i+1 to n-1) if (A[j] < A[min]) min = j; swap A[i] and A[min] } The number of comparisons is our basic operation here. nāˆ’2 nāˆ’2 C(n) = 1 i=0 j=i+1 nāˆ’2 = [(n āˆ’ 1) āˆ’ (i + 1) + 1] i=0 nāˆ’2 = (n āˆ’ 1 āˆ’ i) i=0 (n āˆ’ 1)n = āˆˆ Ī˜(n2 ). 2 Here, we do the same number of comparisons, but at most n āˆ’ 1 = Ī˜(n) swaps. Brute-Force String Match This problem involves searching for a pattern (substring) in a string of text. The basic procedure: 1. Align the pattern at beginning of the text 2. Moving from left to right, compare each character of the pattern to the corresponding char- acter in the text until ā€¢ all characters are found to match (successful search); or ā€¢ a mismatch is detected 3. While pattern is not found and the text is not yet exhausted, realign the pattern one position to the right and repeat Step 2 The result is either the index in the text of the ļ¬rst occurrence of the pattern, or indices of all occurrences. We will look only for the ļ¬rst. Written in pseudocode, our brute-force string match: 3
  • 4. CS 385 Analysis of Algorithms Spring 2011 brute_force_string_match(T[0..n-1], P[0..m-1]) { for (i-0 to n-m) j=0 while (j<m) and P[j] == T[i+j] j++ if j==m return i return -1 } The sizes of the input strings, m for the pattern and n for the text, are the problem size parameters and the basic operation is the element to element comparisons. We have signiļ¬cant differences among the best, average, and worst cases. Best case, we ļ¬nd the pattern at the start of the text and we need only m comparisons: Ī˜(m). In the worst case, we encounter ā€œnear missesā€ at each starting location in the text, requiring about n searches of size m, resulting in Ī˜(nm). On average, however, most non-matches are likely to be detected quickly: in the ļ¬rst element or two, leading to an average case behavior of Ī˜(n). We will consider improvements for string matching later in the semester. Closest Pairs Computational geometry is a rich area for the study of algorithms. Our next problem comes from that ļ¬eld. The problem: Find the two closest points in a set of n points (in the two-dimensional Cartesian plane). Brute-force algorithm: Compute the Euclidean distance between every pair of distinct points and return the indices of the points for which the distance is the smallest. brute_force_closest_points(a set of n points, P) { dmin = infinity for (i=1 to n-1) for (j=i+1 to n) d = sqrt(P[i].x - P[j].x)Ė†2 + (P[i].y - P[j].y)Ė†2)) if (d < dmin) dmin = d index1 = i index2 = j return index1, index2 } The problem size is deļ¬ned by the number of points, n. The basic operation is the computation of the distance between each pair of points. It needs to be computed for each pair of points, so the best, average, and worst cases are the same. 4
  • 5. CS 385 Analysis of Algorithms Spring 2011 Before we continue, however, note that there is a way to improve the efļ¬ciency of this algorithm signiļ¬cantly. Computing square roots is an expensive operation. But if we think about it a bit, itā€™s also completely unnecessary here. Finding the minimum among a collection of square roots is exactly the same as ļ¬nding the minimum among the original numbers. So it can be removed. This leaves us with the squaring of numbers are our basic operation. The number of squaring operations can be computed: nāˆ’1 n C(n) = 2 i=1 j=i+1 nāˆ’1 =2 (n āˆ’ i) i=1 = 2[(n āˆ’ 1) + (n āˆ’ 2) + Ā· Ā· Ā· + 1] = 2(n āˆ’ 1)n āˆˆ Ī˜(n2 ). Convex Hulls Staying in the realm of computational geometry we consider the convex-hull problem. The convex hull of a set of points in the plane is the smallest convex polygon that contains them all. So given a set of points, how can we ļ¬nd the convex hull? First, we should ļ¬nd the extreme points ā€“ those points in our set that lie ā€œon the fringesā€ which will be the vertices of the polygon formed by the points in the convex hull. Second, we need to know in what order to connect them to form the convex polygon. Our brute-force approach is anything but obvious. Our solution will depend on the observation that any line segment connecting two adjacent points on the convex hull will have all other points in the set on the same side of the straight line between its endpoints. Recall from your high school math that the straight line through two points (x1 , y1 ) and (x2 , y2 ) can be deļ¬ned by ax + by = c, a = y2 āˆ’ y1 , b = x1 āˆ’ x2 , c = x1 y2 āˆ’ y1 x2 . We can tell which side of this line any point is by computing ax + by and seeing if it is greater than or less than c. All points where ax + by < c are on one side of the line, those where ax + by > c are on the other. Points on the line will satisfy ax + by = c, of course. So our algorithm will need to consider each pair of points, and see if all other points lie on the same side. If so, the points are part of the convex hull. If not, they are not. brute_force_convex_hull(a set of n points, P) { 5
  • 6. CS 385 Analysis of Algorithms Spring 2011 create empty set of line segments L for (each point p1 in P) for (each point p2 in P after p1) a = p2.y - p1.y; b = p1.x - p2.x; c = p1.x*p2.y - p1.y*p2.x foundProblem = false for (each point p3 in P (not p1 or p2)) check = a*p3.x + b*p3.y - c if (check does not match others) foundProblem=true break if (!foundProblem) add segment p1,p2 to L extract and return list of points from L } See Example: Ėœjteresco/shared/cs385/examples/BruteForceConvexHull For this problem, the size is determined by the number of input points. Its basic operation is the compute of the check in the innermost loop (probably multiplications). For best, average, and worst case behavior, the differences would arise in how quickly we could determine that a given segment is not part of the convex polygon for those that are not. Best case, we would quickly ļ¬nd evidence for those which are not. Worst case, we need to look through most of the points before making a determination. Considering the worst case, we can see that the number of basic operations will be Ī˜(n3 ). Exhaustive Search An exhaustive search is 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. The typical approach involves: 1. Generation of a list of all potential solutions to the problem in a systematic manner (e.g., our permutations from the ļ¬rst problem set ā€“ we will see others). 2. Evaluation of the potential solutions one by one, disqualifying infeasible ones and, for an optimization problem, keeping track of the best one found so far. 3. Announcing the solution when the search ends. We will look brieļ¬‚y at a few examples of problems that can be solved with exhaustive search. 6
  • 7. CS 385 Analysis of Algorithms Spring 2011 Traveling Salesman The traveling salesman problem (TSP) asks us, given n cities with known distances between each pair, ļ¬nd the shortest tour that passes through all the cities exactly once before returning to the starting city. Solutions to this kind of problem have important practical applications (delivery services, census takers, etc.) An alternative statement of the problem is to ļ¬nd the shortest Hamiltonian circuit in a weighted, connected graph. A Hamiltonian circuit is a cycle that passes through all of the vertices of the graph exactly once. If we think about it a bit, we can see that it does not matter where our tour begins and ends ā€“ itā€™s a cycle ā€“ so we can choose any city/vertex as the starting point and consider all permutation of the other n āˆ’ 1 vertices. So an exhaustive search would allow us to consider all (n āˆ’ 1)! permutations, compute the cost (total distance traveled) for each, returning the lowest cost circuit found. The text has a small example. Knapsack Problem Another well-known problem is the knapsack problem. Given n items with weights w1 , w2 , ..., wn and values v1 , v2 , ..., vn , what is the most vaulable subset of items that can ļ¬t into a knapsack that can hold a total weight W . The exhaustive search here involves considering all possible subsets of items and ļ¬nding the subset whose total weight is no more than W with the highest value. For n items, this means we have to generate 2n subsets, giving us that as a lower bound on our cost of ā„¦(2n ). An example of this problem with a knapsack capacity of 16: item weight value 1 2 20 2 5 30 3 10 50 4 5 10 All possible subsets (not including the empty set, which would be the answer only if all items were too heavy to be in the knapsack even alone): 7
  • 8. CS 385 Analysis of Algorithms Spring 2011 subset weight 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 too heavy {1,2,4} 12 60 {1,3,4} 17 too heavy {2,3,4} 20 too heavy {1,2,3,4} 22 too heavy So the winner is {2,3} with a total weight of 15 and a total value of 80. Assignment Problem Our ļ¬nal exhaustive search example is the assignment problem. It may be stated as the assignment of n jobs among n people, one job per person, where the cost of assigning person i to job i is given by C[i, j], and we wish to minimize the total cost across all possible assignments. For example, consider this cost matrix: Job 0 Job 1 Job 2 Job 3 Person 0 9 2 7 8 Person 1 6 4 3 7 Person 2 5 8 1 8 Person 3 7 6 9 4 Our exhaustive search here involves the generation of all possible assignments, computing the total cost of each, and selection of the lowest cost. How many assignments as possible? Well, we can assign the ļ¬rst person any of n jobs. Then, there are n āˆ’ 1 to choose for the second person, n āˆ’ 2 for the third, and so on, until there is just one remaining choice for the last person: a total of n!. We can list the solutions by generating all permutations of the numbers 1, 2, ..., n (sound familiar?), and treating the number in each position as the job to assign to the person at that position. Exhaustive Search Wrapup ā€¢ Exhaustive-search algorithms run in a realistic amount of time only on very small instances. 8
  • 9. CS 385 Analysis of Algorithms Spring 2011 ā€¢ Sometimes, much better approaches exist (and we will see some of those soon). ā€¢ But sometimes, an exhaustive search is the only known way to be guaranteed an exact solu- tion. 9