SlideShare uma empresa Scribd logo
1 de 77
Baixar para ler offline
Computational complexity

Measure the degree of difficulty of an algorithm
Background
 What is an Algorithm?
 A problem can be solved by many algorithms
   E.g., sorting data
 An algorithm is a method or a process followed to solve
 a problem
   I.e., a recipe
 An algorithm takes the input to a problem (function) and
 transforms it to the output
   I.e., a mapping




                          Tecniche di programmazione   A.A. 2012/2013
Why consider Efficiency?
 There are often many algorithms to solve a problem
 How do we choose between them? (Usually) conflicting
 goals:
 To design an algorithm that is easy to understand, code,
 debug
   software engineering
 To design an algorithm that makes efficient use of the
 computer’s resources
   data structures and algorithm analysis




                             Tecniche di programmazione   A.A. 2012/2013
(Un programma che funziona) in fretta
               vs.
Un programma che (funziona in fretta)




                Tecniche di programmazione   A.A. 2012/2013
Why consider Efficiency?
                from the LinkedList javadoc page:
 There are often many algorithms to solve a problem
               “All of the operations perform as could
 How do we choose between them? (Usually) conflicting
 goals:          be expected for a doubly-linked list.”
 To design an algorithm that is easy to understand, code,
 debug
   software engineering
 To design an algorithm that makes efficient use of the
 computer’s resources
   data structures and algorithm analysis




                             Tecniche di programmazione   A.A. 2012/2013
How to Measure Efficiency?
 Critical resources
   programmer’s effort
   time, space (disk, RAM)
 Analysis
   empirical (run programs)
   analytical (asymptotic algorithm analysis)
 Worst case vs. Average case




                              Tecniche di programmazione   A.A. 2012/2013
Empirical Approach
 Implement each candidate
   That could be lots of work – also error-prone
 Run it
   Which inputs?
   Worst case, average case, or best case?
 Time it
   What machines
   Which OS?




                             Tecniche di programmazione   A.A. 2012/2013
Analytical Approach
 How to solve “which algorithm” problems without
 machines nor test data?




                        Tecniche di programmazione   A.A. 2012/2013
Analytical Approach
 An algorithm is a mapping
 For most algorithms, running time depends on “size” of
 the input
 Running time is expressed as T(n)
   some function T
   input size n




                          Tecniche di programmazione   A.A. 2012/2013
Bubble sort




              Tecniche di programmazione   A.A. 2012/2013
Analysis
 The bubble sort takes (n2-n)/2 “steps”
 Different implementations/assembly languages
  Program A on an Intel Pentium IV: T(n) = 58*(n2-n)/2
  Program B on a Motorola: T(n) = 84*(n2-2n)/2
  Program C on an Intel Pentium V: T(n) = 44*(n2-n)/2
 Note that each has an n2 term
  as n increases, the other terms
  will drop out




                            Tecniche di programmazione   A.A. 2012/2013
Analysis
 As a result:
   Program A on Intel Pentium IV: T(n) ≈ 29n2
   Program B on Motorola: T(n) ≈ 42n2
   Program C on Intel Pentium V: T(n) ≈ 22n2




                             Tecniche di programmazione   A.A. 2012/2013
Analysis
 As processors change, the constants will always change
   The exponent on n will not
   We should not care about the constants
 As a result:
   Program A: T(n) ≈ n2
   Program B: T(n) ≈ n2
   Program C: T(n) ≈ n2


 Bubble sort: T(n) ≈ n2



                           Tecniche di programmazione   A.A. 2012/2013
Intuitive motivations
 Asymptotic notation captures behavior of functions for
 large values of x.
 Dominant term of 3x3 + 5x2 – 9 is 3x3
 As x becomes larger and larger, other terms become
 insignificant and only 3x3 remains in the picture




                          Tecniche di programmazione   A.A. 2012/2013
[0, 2]

         y = 3x 3+5x 2 –9                        y=x3


                                                 y=x2
                                                 y=x




          Tecniche di programmazione   A.A. 2012/2013
[0, 5]




         Tecniche di programmazione   A.A. 2012/2013
[0, 10]




          Tecniche di programmazione   A.A. 2012/2013
[0, 100]

                                    y = 5x 3




                          y = 3x 3+5x 2 –9




           Tecniche di programmazione   A.A. 2012/2013
Complexity Analysis
 O( · )
   big o (big oh)
 Ω( · )
 big omega
 Θ( · )
   big theta




                    Tecniche di programmazione   A.A. 2012/2013
O( · )
 Upper Bounding Running Time
 Why?
   Little-oh
   “Order of”
   D’Oh




                                                                     Oh!




                       Tecniche di programmazione   A.A. 2012/2013
Upper Bounding Running Time
 f(n) is O(g(n)) if f grows “at most as fast as” g




21                       Tecniche di programmazione   A.A. 2012/2013
Big-O (formal)
 Let f and g be two functions such that
            f (n ) : N → R + and g (n ) : N → R +

 if there exists positive constants c and n0 such that
                 f (n ) ≤ cg (n ), for all n > n0

 then we can write
                     f (n ) = O( g (n ))


22                           Tecniche di programmazione   A.A. 2012/2013
Big-O (formal alt)
 Let f and g be two functions such that
            f (n ) : N → R + and g (n ) : N → R +

 if there exists positive constants c and n0 such that
                              f (n )
                     0 ≤ lim         =c<∞
                         n →∞ g (n )


 then we can write
                     f (n ) = O( g (n ))


23                          Tecniche di programmazione   A.A. 2012/2013
Example
 (log n)2 = O(n)




24                 Tecniche di programmazione   A.A. 2012/2013
Notational Issues
 Big-O notation is a way of comparing functions
 Notation quite unconventional
   e.g., 3x3 + 5x2 – 9 = O(x3)
 Doesn’t mean
 “3x3 + 5x2 – 9 equals the function O(x3)”
 “3x3 + 5x2 – 9 is big oh of x3”
 But
   “3x3+5x2 –9 is dominated by x3”




                                 Tecniche di programmazione   A.A. 2012/2013
Common Misunderstanding
 3x3 + 5x2 – 9 = O(x3)
 However, also true are:
   3x3 + 5x2 – 9 = O(x4)
   x3 = O(3x3 + 5x2 – 9)
   sin(x) = O(x4)
 Note:
   Usage of big-O typically involves mentioning
   only the most dominant term
   “The running time is O(x2.5)”




                             Tecniche di programmazione   A.A. 2012/2013
Lower Bounding Running Time
 f(n) is Ω(g(n)) if f grows “at least as fast as” g




 cg(n) is an approximation to f(n) bounding from below

27                        Tecniche di programmazione   A.A. 2012/2013
Big-Omega (formal)
 Let f and g be two functions such that
            f (n ) : N → R + and g (n ) : N → R +

 if there exists positive constants c and n0 such that
                 f (n ) ≥ cg (n ), for all n > n0

 then we can write
                     f (n ) = Ω( g (n ))


28                           Tecniche di programmazione   A.A. 2012/2013
Tightly Bounding Running Time
 f(n) is Θ(g(n)) if f is essentially the same as g, to
 within a constant multiple




29                         Tecniche di programmazione   A.A. 2012/2013
Big-Theta (formal)
 Let f and g be two functions such that
             f (n ) : N → R + and g (n ) : N → R +

 if there exists positive constants c1, c2 and n0 such that
           c1 g (n ) ≤ f (n ) ≤ c2 g (n ), for all n > n0

 then we can write
                      f (n ) = Θ( g (n ))


30                            Tecniche di programmazione   A.A. 2012/2013
Big-Θ, Big-O, and Big-Ω




31               Tecniche di programmazione   A.A. 2012/2013
Big-Ω and Big-Θ
 Big-Ω: reverse of big-O. I.e.
                     f (x ) = Ω(g (x ))
                              iff
                     g (x ) = O (f (x ))
 so f(x) asymptotically dominates g(x)




                            Tecniche di programmazione   A.A. 2012/2013
Big-Ω and Big-Θ
 Big-Θ: domination in both directions. I.e.
                     f (x ) = Θ(g (x ))
                             iff
         f (x ) = O (g (x )) && f (x ) = Ω(g (x ))




                           Tecniche di programmazione   A.A. 2012/2013
Problem
 Order the following from smallest to largest
 asymptotically. Group together all functions which are
 big-Θ of each other:


                        1       1
x + sin x, ln x, x + x , ,13 + ,13 + x, e , x , x
                                            x    e  x

                        x       x
   ( x + sin x)( x − 102), x ln x, x(ln x) , lg 2 x
                  20                      2




                          Tecniche di programmazione   A.A. 2012/2013
Solution
  1x
  13 + 1 x
 ln x lg 2 x
  x + sin x, x + x ,13 + x
  x ln x
          2
  x(ln x)
     e
   x
  ( x + sin x)( x 20 − 102)
     x
   e
   xx
                              Tecniche di programmazione   A.A. 2012/2013
Practical approach




36               Tecniche di programmazione   A.A. 2012/2013
Practical approach




37               Tecniche di programmazione   A.A. 2012/2013
38   Tecniche di programmazione   A.A. 2012/2013
Would it be possible?
     Algorithm     Foo                         Bar
     Complexity   O(n2)                        O(2n)
     n = 100        10s                         4s
     n = 1000       12s                        4.5s




39                Tecniche di programmazione    A.A. 2012/2013
Determination of Time Complexity
 Because of the approximations available through Big-Oh ,
 the actual T(n) of an algorithm is not calculated
     T(n) may be determined empirically
 Big-Oh is usually determined by application of some
 simple 5 rules




40                            Tecniche di programmazione   A.A. 2012/2013
Rule #1
 Simple program statements are assumed to take a
 constant amount of time which is
                         O(1)




41                       Tecniche di programmazione   A.A. 2012/2013
Rule #2
 Differences in execution time of simple statements is
 ignored




42                        Tecniche di programmazione   A.A. 2012/2013
Rule #3
 In conditional statements the worst case is always used




43                        Tecniche di programmazione   A.A. 2012/2013
Rule #4 – the “sum” rule
 The running time of a sequence of steps has the order of
 the running time of the largest
 E.g.,
     f(n) = O(n2)
     g(n) = O(n3)
     f(n) + g(n) = O(n3)




44                         Tecniche di programmazione   A.A. 2012/2013
Rule #5 – the “product” rule
 If two processes are constructed such that second
 process is repeated a number of times for each n in the
 first process, then O is equal to the product of the orders
 of magnitude for both products
 E.g.,
     For example, a two-dimensional array has one for loop inside
     another and each internal loop is executed n times for each
     value of the external loop.
     The function is O(n2)




45                             Tecniche di programmazione   A.A. 2012/2013
Nested Loops



for(int t=0; t<n; ++t) {
         for(int u=0; u<n; ++u) {     O(n)
             ++zap;                  O(1)
         }
}




    46                          Tecniche di programmazione   A.A. 2012/2013
Nested Loops



for(int t=0; t<n; ++t) {
         for(int u=0; u<n; ++u) {
             ++zap;                      O(n*1)
         }
}




    47                          Tecniche di programmazione   A.A. 2012/2013
Nested Loops



for(int t=0; t<n; ++t) {                 O(n)
         for(int u=0; u<n; ++u) {
             ++zap;                      O(n)
         }
}




    48                          Tecniche di programmazione   A.A. 2012/2013
Nested Loops



for(int t=0; t<n; ++t) {
         for(int u=0; u<n; ++u) {
             ++zap;                      O(n2)
         }
}




    49                          Tecniche di programmazione   A.A. 2012/2013
Nested Loops
     Note: Running time grows with nesting rather than the
     length of the code

for(int t=0; t<n; ++t) {
         for(int u=0; u<n; ++u) {
             ++zap;                      O(n2)
         }
}




    50                          Tecniche di programmazione   A.A. 2012/2013
More Nested Loops

for(int t=0; t<n; ++t) {
         for(int u=t; u<n; ++u) {               n−t
             ++zap;
         }
}




                               n(n − 1) n 2 − n
              ∑i =0 (n − i ) =
                 n −1

                                  2
                                       =
                                           2
                                                =O n 2
                                                                ( )
    51                           Tecniche di programmazione   A.A. 2012/2013
Sequential statements

for(int z=0; z<n; ++z)
         zap[z] = 0;
                                O(n)
for(int t=0; t<n; ++t) {
         for(int u=t; u<n; ++u) {
             ++zap;                    O(n2)
         }
}




     Running time: max(O(n), O(n2)) = O(n2)

    52                          Tecniche di programmazione   A.A. 2012/2013
Conditionals

for(int t=0; t<n; ++t) {
         if(t%2) {
             for(int u=t; u<n; ++u) {
                 ++zap;                         O(n)
             }
         } else {
             zap = 0;      O(1)
         }
}




    53                            Tecniche di programmazione   A.A. 2012/2013
Conditionals

for(int t=0; t<n; ++t) {
         if(t%2) {
             for(int u=t; u<n; ++u) {
                 ++zap;
             }                                 O(n2)
         } else {
             zap = 0;
         }
}




    54                           Tecniche di programmazione   A.A. 2012/2013
55   Tecniche di programmazione   A.A. 2012/2013
Tips
 Focus only on the dominant (high cost) operations and
 avoid a line-by-line exact analysis
 Break algorithm down into “known” pieces
 Identify relationships between pieces
     Sequential is additive
     Nested (loop / recursion) is multiplicative
 Drop constants
 Keep only dominant factor for each variable




56                              Tecniche di programmazione   A.A. 2012/2013
Caveats
 Real time vs. complexity




57                          Tecniche di programmazione   A.A. 2012/2013
Caveats
 Real time vs. complexity
 CPU time vs. RAM vs. disk




58                       Tecniche di programmazione   A.A. 2012/2013
Caveats
 Real time vs. complexity
 CPU time vs. RAM vs. disk
 Worse, Average or Best Case?




59                      Tecniche di programmazione   A.A. 2012/2013
Worse, Average or Best Case?




60
Worse, Average or Best Case?
 Depends on input problem instance type




61
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Basic Asymptotic Efficiency Classes
Evaluate the complexity
 Linear search?




70                Tecniche di programmazione   A.A. 2012/2013
Evaluate the complexity
 Linear search
     O(n)
 Dichotomic search




71                   Tecniche di programmazione   A.A. 2012/2013
Evaluate the complexity
 Linear search
     O(n)
 Dichotomic search
     O(log(n))




72                   Tecniche di programmazione   A.A. 2012/2013
Basic Asymptotic Efficiency Classes
ArrayList vs. LinkedList
                      ArrayList                        LinkedList
add(element)
remove(object)
get(index)
set(index, element)
add(index, element)
remove(index)
contains(object)
indexOf(object)




 74                    Tecniche di programmazione   A.A. 2012/2013
ArrayList vs. LinkedList
                       ArrayList                        LinkedList
add(element)             O(1)                               O(1)
remove(object)        O(n) + O(n)                      O(n) + O(1)
get(index)               O(1)                               O(n)
set(index, element)      O(1)                          O(n) + O(1)
add(index, element)   O(1) + O(n)                      O(n) + O(1)
remove(index)            O(n)                          O(n) + O(1)
contains(object)         O(n)                               O(n)
indexOf(object)          O(n)                               O(n)




 75                     Tecniche di programmazione   A.A. 2012/2013
In theory, there is no difference
between theory and practice.




76               Tecniche di programmazione   A.A. 2012/2013
Licenza d’uso
 Queste diapositive sono distribuite con licenza Creative Commons
 “Attribuzione - Non commerciale - Condividi allo stesso modo (CC
 BY-NC-SA)”
 Sei libero:
     di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,
     rappresentare, eseguire e recitare quest'opera
     di modificare quest'opera
 Alle seguenti condizioni:
     Attribuzione — Devi attribuire la paternità dell'opera agli autori
     originali e in modo tale da non suggerire che essi avallino te o il modo in
     cui tu usi l'opera.
     Non commerciale — Non puoi usare quest'opera per fini
     commerciali.
     Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se
     la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una
     licenza identica o equivalente a questa.
 http://creativecommons.org/licenses/by-nc-sa/3.0/
77                                   Tecniche di programmazione   A.A. 2012/2013

Mais conteúdo relacionado

Mais procurados

Ads unit 3 ppt
Ads unit 3 pptAds unit 3 ppt
Ads unit 3 pptpraveena p
 
Srinivas Reddy Amedapu C and Data Structures JNTUH Hyderabad
Srinivas Reddy Amedapu C and Data Structures JNTUH HyderabadSrinivas Reddy Amedapu C and Data Structures JNTUH Hyderabad
Srinivas Reddy Amedapu C and Data Structures JNTUH HyderabadSrinivas Reddy Amedapu
 
Mixed-integer and Disjunctive Programming - Ignacio E. Grossmann
Mixed-integer and Disjunctive Programming - Ignacio E. GrossmannMixed-integer and Disjunctive Programming - Ignacio E. Grossmann
Mixed-integer and Disjunctive Programming - Ignacio E. GrossmannCAChemE
 
Matrix multiplicationdesign
Matrix multiplicationdesignMatrix multiplicationdesign
Matrix multiplicationdesignRespa Peter
 
Tech Talks @NSU: DLang: возможности языка и его применение
Tech Talks @NSU: DLang: возможности языка и его применениеTech Talks @NSU: DLang: возможности языка и его применение
Tech Talks @NSU: DLang: возможности языка и его применениеTech Talks @NSU
 
Quantum Business in Japanese Market
Quantum Business in Japanese MarketQuantum Business in Japanese Market
Quantum Business in Japanese MarketYuichiro MInato
 
GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004Rohit Garg
 
Programming workshop
Programming workshopProgramming workshop
Programming workshopSandeep Joshi
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programmingOye Tu
 

Mais procurados (17)

Convex hull in 3D
Convex hull in 3DConvex hull in 3D
Convex hull in 3D
 
Ads unit 3 ppt
Ads unit 3 pptAds unit 3 ppt
Ads unit 3 ppt
 
C lab excellent
C lab excellentC lab excellent
C lab excellent
 
C and Data Structures
C and Data Structures C and Data Structures
C and Data Structures
 
Srinivas Reddy Amedapu C and Data Structures JNTUH Hyderabad
Srinivas Reddy Amedapu C and Data Structures JNTUH HyderabadSrinivas Reddy Amedapu C and Data Structures JNTUH Hyderabad
Srinivas Reddy Amedapu C and Data Structures JNTUH Hyderabad
 
Mixed-integer and Disjunctive Programming - Ignacio E. Grossmann
Mixed-integer and Disjunctive Programming - Ignacio E. GrossmannMixed-integer and Disjunctive Programming - Ignacio E. Grossmann
Mixed-integer and Disjunctive Programming - Ignacio E. Grossmann
 
Unit 3 daa
Unit 3 daaUnit 3 daa
Unit 3 daa
 
Matrix multiplicationdesign
Matrix multiplicationdesignMatrix multiplicationdesign
Matrix multiplicationdesign
 
Boyd 4.6, 4.7
Boyd 4.6, 4.7Boyd 4.6, 4.7
Boyd 4.6, 4.7
 
Tech Talks @NSU: DLang: возможности языка и его применение
Tech Talks @NSU: DLang: возможности языка и его применениеTech Talks @NSU: DLang: возможности языка и его применение
Tech Talks @NSU: DLang: возможности языка и его применение
 
13slide graphics
13slide graphics13slide graphics
13slide graphics
 
Triggering patterns of topology changes in dynamic attributed graphs
Triggering patterns of topology changes in dynamic attributed graphsTriggering patterns of topology changes in dynamic attributed graphs
Triggering patterns of topology changes in dynamic attributed graphs
 
Quantum Business in Japanese Market
Quantum Business in Japanese MarketQuantum Business in Japanese Market
Quantum Business in Japanese Market
 
GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004
 
Programming workshop
Programming workshopProgramming workshop
Programming workshop
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
Unit 5
Unit 5Unit 5
Unit 5
 

Destaque

Ausili definizioni e normative
Ausili definizioni e normativeAusili definizioni e normative
Ausili definizioni e normativeFulvio Corno
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programmingFulvio Corno
 
Search and Optimization Strategies
Search and Optimization StrategiesSearch and Optimization Strategies
Search and Optimization StrategiesFulvio Corno
 
Presentazione Servizio Poli@Home
Presentazione Servizio Poli@HomePresentazione Servizio Poli@Home
Presentazione Servizio Poli@HomeFulvio Corno
 
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)Fulvio Corno
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programmingFulvio Corno
 
Linked Data for Ambient Intelligence
Linked Data for Ambient IntelligenceLinked Data for Ambient Intelligence
Linked Data for Ambient IntelligenceFulvio Corno
 
Accessibilità dei siti web
Accessibilità dei siti webAccessibilità dei siti web
Accessibilità dei siti webFulvio Corno
 
Logic and Reasoning in the Semantic Web (part II –OWL)
Logic and Reasoning in the Semantic Web (part II –OWL)Logic and Reasoning in the Semantic Web (part II –OWL)
Logic and Reasoning in the Semantic Web (part II –OWL)Fulvio Corno
 
Logic and Reasoning in the Semantic Web
Logic and Reasoning in the Semantic WebLogic and Reasoning in the Semantic Web
Logic and Reasoning in the Semantic WebFulvio Corno
 
Lucidi relativi al DVD di Programmazione in C
Lucidi relativi al DVD di Programmazione in CLucidi relativi al DVD di Programmazione in C
Lucidi relativi al DVD di Programmazione in CFulvio Corno
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryFulvio Corno
 
Introduction to SKOS - Simple Knowledge Organization System
Introduction to SKOS - Simple Knowledge Organization SystemIntroduction to SKOS - Simple Knowledge Organization System
Introduction to SKOS - Simple Knowledge Organization SystemFulvio Corno
 
Semantic Web, Metadata, Knowledge Representation, Ontologies
Semantic Web, Metadata, Knowledge Representation, OntologiesSemantic Web, Metadata, Knowledge Representation, Ontologies
Semantic Web, Metadata, Knowledge Representation, OntologiesFulvio Corno
 
Complete Guide to Seo Footprints
Complete Guide to Seo FootprintsComplete Guide to Seo Footprints
Complete Guide to Seo FootprintsPritesh Das
 

Destaque (18)

Ausili definizioni e normative
Ausili definizioni e normativeAusili definizioni e normative
Ausili definizioni e normative
 
Web Accessibility
Web AccessibilityWeb Accessibility
Web Accessibility
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
Search and Optimization Strategies
Search and Optimization StrategiesSearch and Optimization Strategies
Search and Optimization Strategies
 
Presentazione Servizio Poli@Home
Presentazione Servizio Poli@HomePresentazione Servizio Poli@Home
Presentazione Servizio Poli@Home
 
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
Logic and Reasoning in the Semantic Web (part I –RDF/RDFS)
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
 
Linked Data for Ambient Intelligence
Linked Data for Ambient IntelligenceLinked Data for Ambient Intelligence
Linked Data for Ambient Intelligence
 
Accessibilità dei siti web
Accessibilità dei siti webAccessibilità dei siti web
Accessibilità dei siti web
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Logic and Reasoning in the Semantic Web (part II –OWL)
Logic and Reasoning in the Semantic Web (part II –OWL)Logic and Reasoning in the Semantic Web (part II –OWL)
Logic and Reasoning in the Semantic Web (part II –OWL)
 
Logic and Reasoning in the Semantic Web
Logic and Reasoning in the Semantic WebLogic and Reasoning in the Semantic Web
Logic and Reasoning in the Semantic Web
 
Lucidi relativi al DVD di Programmazione in C
Lucidi relativi al DVD di Programmazione in CLucidi relativi al DVD di Programmazione in C
Lucidi relativi al DVD di Programmazione in C
 
Web Transactions
Web TransactionsWeb Transactions
Web Transactions
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP library
 
Introduction to SKOS - Simple Knowledge Organization System
Introduction to SKOS - Simple Knowledge Organization SystemIntroduction to SKOS - Simple Knowledge Organization System
Introduction to SKOS - Simple Knowledge Organization System
 
Semantic Web, Metadata, Knowledge Representation, Ontologies
Semantic Web, Metadata, Knowledge Representation, OntologiesSemantic Web, Metadata, Knowledge Representation, Ontologies
Semantic Web, Metadata, Knowledge Representation, Ontologies
 
Complete Guide to Seo Footprints
Complete Guide to Seo FootprintsComplete Guide to Seo Footprints
Complete Guide to Seo Footprints
 

Semelhante a Computational complexity

DAA-Unit1.pptx
DAA-Unit1.pptxDAA-Unit1.pptx
DAA-Unit1.pptxNishaS88
 
Introduction to Algorithms and Asymptotic Notation
Introduction to Algorithms and Asymptotic NotationIntroduction to Algorithms and Asymptotic Notation
Introduction to Algorithms and Asymptotic NotationAmrinder Arora
 
how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihmSajid Marwat
 
Cs6402 daa-2 marks set 1
Cs6402 daa-2 marks set 1Cs6402 daa-2 marks set 1
Cs6402 daa-2 marks set 1Vai Jayanthi
 
analysis of algorithms
analysis of algorithmsanalysis of algorithms
analysis of algorithmsMyMovies15
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm AnalysisMary Margarat
 
Data_Structure_and_Algorithms_Lecture_1.ppt
Data_Structure_and_Algorithms_Lecture_1.pptData_Structure_and_Algorithms_Lecture_1.ppt
Data_Structure_and_Algorithms_Lecture_1.pptISHANAMRITSRIVASTAVA
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues listsJames Wong
 

Semelhante a Computational complexity (20)

Unit 1
Unit 1Unit 1
Unit 1
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpall...
Algorithm Class at KPHB  (C, C++ Course Training Institute in KPHB, Kukatpall...Algorithm Class at KPHB  (C, C++ Course Training Institute in KPHB, Kukatpall...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpall...
 
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
Algorithm Class at KPHB (C, C++ Course Training Institute in KPHB, Kukatpally...
 
analysis.ppt
analysis.pptanalysis.ppt
analysis.ppt
 
Analysis of Algorithum
Analysis of AlgorithumAnalysis of Algorithum
Analysis of Algorithum
 
DAA-Unit1.pptx
DAA-Unit1.pptxDAA-Unit1.pptx
DAA-Unit1.pptx
 
Introduction to Algorithms and Asymptotic Notation
Introduction to Algorithms and Asymptotic NotationIntroduction to Algorithms and Asymptotic Notation
Introduction to Algorithms and Asymptotic Notation
 
Time complexity.ppt
Time complexity.pptTime complexity.ppt
Time complexity.ppt
 
how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihm
 
3 analysis.gtm
3 analysis.gtm3 analysis.gtm
3 analysis.gtm
 
Lec1
Lec1Lec1
Lec1
 
Cs6402 daa-2 marks set 1
Cs6402 daa-2 marks set 1Cs6402 daa-2 marks set 1
Cs6402 daa-2 marks set 1
 
Lec7
Lec7Lec7
Lec7
 
Lec7.ppt
Lec7.pptLec7.ppt
Lec7.ppt
 
Lec7.ppt
Lec7.pptLec7.ppt
Lec7.ppt
 
analysis of algorithms
analysis of algorithmsanalysis of algorithms
analysis of algorithms
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
Data_Structure_and_Algorithms_Lecture_1.ppt
Data_Structure_and_Algorithms_Lecture_1.pptData_Structure_and_Algorithms_Lecture_1.ppt
Data_Structure_and_Algorithms_Lecture_1.ppt
 
Stack squeues lists
Stack squeues listsStack squeues lists
Stack squeues lists
 

Último

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Último (20)

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

Computational complexity

  • 1. Computational complexity Measure the degree of difficulty of an algorithm
  • 2. Background What is an Algorithm? A problem can be solved by many algorithms E.g., sorting data An algorithm is a method or a process followed to solve a problem I.e., a recipe An algorithm takes the input to a problem (function) and transforms it to the output I.e., a mapping Tecniche di programmazione A.A. 2012/2013
  • 3. Why consider Efficiency? There are often many algorithms to solve a problem How do we choose between them? (Usually) conflicting goals: To design an algorithm that is easy to understand, code, debug software engineering To design an algorithm that makes efficient use of the computer’s resources data structures and algorithm analysis Tecniche di programmazione A.A. 2012/2013
  • 4. (Un programma che funziona) in fretta vs. Un programma che (funziona in fretta) Tecniche di programmazione A.A. 2012/2013
  • 5. Why consider Efficiency? from the LinkedList javadoc page: There are often many algorithms to solve a problem “All of the operations perform as could How do we choose between them? (Usually) conflicting goals: be expected for a doubly-linked list.” To design an algorithm that is easy to understand, code, debug software engineering To design an algorithm that makes efficient use of the computer’s resources data structures and algorithm analysis Tecniche di programmazione A.A. 2012/2013
  • 6. How to Measure Efficiency? Critical resources programmer’s effort time, space (disk, RAM) Analysis empirical (run programs) analytical (asymptotic algorithm analysis) Worst case vs. Average case Tecniche di programmazione A.A. 2012/2013
  • 7. Empirical Approach Implement each candidate That could be lots of work – also error-prone Run it Which inputs? Worst case, average case, or best case? Time it What machines Which OS? Tecniche di programmazione A.A. 2012/2013
  • 8. Analytical Approach How to solve “which algorithm” problems without machines nor test data? Tecniche di programmazione A.A. 2012/2013
  • 9. Analytical Approach An algorithm is a mapping For most algorithms, running time depends on “size” of the input Running time is expressed as T(n) some function T input size n Tecniche di programmazione A.A. 2012/2013
  • 10. Bubble sort Tecniche di programmazione A.A. 2012/2013
  • 11. Analysis The bubble sort takes (n2-n)/2 “steps” Different implementations/assembly languages Program A on an Intel Pentium IV: T(n) = 58*(n2-n)/2 Program B on a Motorola: T(n) = 84*(n2-2n)/2 Program C on an Intel Pentium V: T(n) = 44*(n2-n)/2 Note that each has an n2 term as n increases, the other terms will drop out Tecniche di programmazione A.A. 2012/2013
  • 12. Analysis As a result: Program A on Intel Pentium IV: T(n) ≈ 29n2 Program B on Motorola: T(n) ≈ 42n2 Program C on Intel Pentium V: T(n) ≈ 22n2 Tecniche di programmazione A.A. 2012/2013
  • 13. Analysis As processors change, the constants will always change The exponent on n will not We should not care about the constants As a result: Program A: T(n) ≈ n2 Program B: T(n) ≈ n2 Program C: T(n) ≈ n2 Bubble sort: T(n) ≈ n2 Tecniche di programmazione A.A. 2012/2013
  • 14. Intuitive motivations Asymptotic notation captures behavior of functions for large values of x. Dominant term of 3x3 + 5x2 – 9 is 3x3 As x becomes larger and larger, other terms become insignificant and only 3x3 remains in the picture Tecniche di programmazione A.A. 2012/2013
  • 15. [0, 2] y = 3x 3+5x 2 –9 y=x3 y=x2 y=x Tecniche di programmazione A.A. 2012/2013
  • 16. [0, 5] Tecniche di programmazione A.A. 2012/2013
  • 17. [0, 10] Tecniche di programmazione A.A. 2012/2013
  • 18. [0, 100] y = 5x 3 y = 3x 3+5x 2 –9 Tecniche di programmazione A.A. 2012/2013
  • 19. Complexity Analysis O( · ) big o (big oh) Ω( · ) big omega Θ( · ) big theta Tecniche di programmazione A.A. 2012/2013
  • 20. O( · ) Upper Bounding Running Time Why? Little-oh “Order of” D’Oh Oh! Tecniche di programmazione A.A. 2012/2013
  • 21. Upper Bounding Running Time f(n) is O(g(n)) if f grows “at most as fast as” g 21 Tecniche di programmazione A.A. 2012/2013
  • 22. Big-O (formal) Let f and g be two functions such that f (n ) : N → R + and g (n ) : N → R + if there exists positive constants c and n0 such that f (n ) ≤ cg (n ), for all n > n0 then we can write f (n ) = O( g (n )) 22 Tecniche di programmazione A.A. 2012/2013
  • 23. Big-O (formal alt) Let f and g be two functions such that f (n ) : N → R + and g (n ) : N → R + if there exists positive constants c and n0 such that f (n ) 0 ≤ lim =c<∞ n →∞ g (n ) then we can write f (n ) = O( g (n )) 23 Tecniche di programmazione A.A. 2012/2013
  • 24. Example (log n)2 = O(n) 24 Tecniche di programmazione A.A. 2012/2013
  • 25. Notational Issues Big-O notation is a way of comparing functions Notation quite unconventional e.g., 3x3 + 5x2 – 9 = O(x3) Doesn’t mean “3x3 + 5x2 – 9 equals the function O(x3)” “3x3 + 5x2 – 9 is big oh of x3” But “3x3+5x2 –9 is dominated by x3” Tecniche di programmazione A.A. 2012/2013
  • 26. Common Misunderstanding 3x3 + 5x2 – 9 = O(x3) However, also true are: 3x3 + 5x2 – 9 = O(x4) x3 = O(3x3 + 5x2 – 9) sin(x) = O(x4) Note: Usage of big-O typically involves mentioning only the most dominant term “The running time is O(x2.5)” Tecniche di programmazione A.A. 2012/2013
  • 27. Lower Bounding Running Time f(n) is Ω(g(n)) if f grows “at least as fast as” g cg(n) is an approximation to f(n) bounding from below 27 Tecniche di programmazione A.A. 2012/2013
  • 28. Big-Omega (formal) Let f and g be two functions such that f (n ) : N → R + and g (n ) : N → R + if there exists positive constants c and n0 such that f (n ) ≥ cg (n ), for all n > n0 then we can write f (n ) = Ω( g (n )) 28 Tecniche di programmazione A.A. 2012/2013
  • 29. Tightly Bounding Running Time f(n) is Θ(g(n)) if f is essentially the same as g, to within a constant multiple 29 Tecniche di programmazione A.A. 2012/2013
  • 30. Big-Theta (formal) Let f and g be two functions such that f (n ) : N → R + and g (n ) : N → R + if there exists positive constants c1, c2 and n0 such that c1 g (n ) ≤ f (n ) ≤ c2 g (n ), for all n > n0 then we can write f (n ) = Θ( g (n )) 30 Tecniche di programmazione A.A. 2012/2013
  • 31. Big-Θ, Big-O, and Big-Ω 31 Tecniche di programmazione A.A. 2012/2013
  • 32. Big-Ω and Big-Θ Big-Ω: reverse of big-O. I.e. f (x ) = Ω(g (x )) iff g (x ) = O (f (x )) so f(x) asymptotically dominates g(x) Tecniche di programmazione A.A. 2012/2013
  • 33. Big-Ω and Big-Θ Big-Θ: domination in both directions. I.e. f (x ) = Θ(g (x )) iff f (x ) = O (g (x )) && f (x ) = Ω(g (x )) Tecniche di programmazione A.A. 2012/2013
  • 34. Problem Order the following from smallest to largest asymptotically. Group together all functions which are big-Θ of each other: 1 1 x + sin x, ln x, x + x , ,13 + ,13 + x, e , x , x x e x x x ( x + sin x)( x − 102), x ln x, x(ln x) , lg 2 x 20 2 Tecniche di programmazione A.A. 2012/2013
  • 35. Solution 1x 13 + 1 x ln x lg 2 x x + sin x, x + x ,13 + x x ln x 2 x(ln x) e x ( x + sin x)( x 20 − 102) x e xx Tecniche di programmazione A.A. 2012/2013
  • 36. Practical approach 36 Tecniche di programmazione A.A. 2012/2013
  • 37. Practical approach 37 Tecniche di programmazione A.A. 2012/2013
  • 38. 38 Tecniche di programmazione A.A. 2012/2013
  • 39. Would it be possible? Algorithm Foo Bar Complexity O(n2) O(2n) n = 100 10s 4s n = 1000 12s 4.5s 39 Tecniche di programmazione A.A. 2012/2013
  • 40. Determination of Time Complexity Because of the approximations available through Big-Oh , the actual T(n) of an algorithm is not calculated T(n) may be determined empirically Big-Oh is usually determined by application of some simple 5 rules 40 Tecniche di programmazione A.A. 2012/2013
  • 41. Rule #1 Simple program statements are assumed to take a constant amount of time which is O(1) 41 Tecniche di programmazione A.A. 2012/2013
  • 42. Rule #2 Differences in execution time of simple statements is ignored 42 Tecniche di programmazione A.A. 2012/2013
  • 43. Rule #3 In conditional statements the worst case is always used 43 Tecniche di programmazione A.A. 2012/2013
  • 44. Rule #4 – the “sum” rule The running time of a sequence of steps has the order of the running time of the largest E.g., f(n) = O(n2) g(n) = O(n3) f(n) + g(n) = O(n3) 44 Tecniche di programmazione A.A. 2012/2013
  • 45. Rule #5 – the “product” rule If two processes are constructed such that second process is repeated a number of times for each n in the first process, then O is equal to the product of the orders of magnitude for both products E.g., For example, a two-dimensional array has one for loop inside another and each internal loop is executed n times for each value of the external loop. The function is O(n2) 45 Tecniche di programmazione A.A. 2012/2013
  • 46. Nested Loops for(int t=0; t<n; ++t) { for(int u=0; u<n; ++u) { O(n) ++zap; O(1) } } 46 Tecniche di programmazione A.A. 2012/2013
  • 47. Nested Loops for(int t=0; t<n; ++t) { for(int u=0; u<n; ++u) { ++zap; O(n*1) } } 47 Tecniche di programmazione A.A. 2012/2013
  • 48. Nested Loops for(int t=0; t<n; ++t) { O(n) for(int u=0; u<n; ++u) { ++zap; O(n) } } 48 Tecniche di programmazione A.A. 2012/2013
  • 49. Nested Loops for(int t=0; t<n; ++t) { for(int u=0; u<n; ++u) { ++zap; O(n2) } } 49 Tecniche di programmazione A.A. 2012/2013
  • 50. Nested Loops Note: Running time grows with nesting rather than the length of the code for(int t=0; t<n; ++t) { for(int u=0; u<n; ++u) { ++zap; O(n2) } } 50 Tecniche di programmazione A.A. 2012/2013
  • 51. More Nested Loops for(int t=0; t<n; ++t) { for(int u=t; u<n; ++u) { n−t ++zap; } } n(n − 1) n 2 − n ∑i =0 (n − i ) = n −1 2 = 2 =O n 2 ( ) 51 Tecniche di programmazione A.A. 2012/2013
  • 52. Sequential statements for(int z=0; z<n; ++z) zap[z] = 0; O(n) for(int t=0; t<n; ++t) { for(int u=t; u<n; ++u) { ++zap; O(n2) } } Running time: max(O(n), O(n2)) = O(n2) 52 Tecniche di programmazione A.A. 2012/2013
  • 53. Conditionals for(int t=0; t<n; ++t) { if(t%2) { for(int u=t; u<n; ++u) { ++zap; O(n) } } else { zap = 0; O(1) } } 53 Tecniche di programmazione A.A. 2012/2013
  • 54. Conditionals for(int t=0; t<n; ++t) { if(t%2) { for(int u=t; u<n; ++u) { ++zap; } O(n2) } else { zap = 0; } } 54 Tecniche di programmazione A.A. 2012/2013
  • 55. 55 Tecniche di programmazione A.A. 2012/2013
  • 56. Tips Focus only on the dominant (high cost) operations and avoid a line-by-line exact analysis Break algorithm down into “known” pieces Identify relationships between pieces Sequential is additive Nested (loop / recursion) is multiplicative Drop constants Keep only dominant factor for each variable 56 Tecniche di programmazione A.A. 2012/2013
  • 57. Caveats Real time vs. complexity 57 Tecniche di programmazione A.A. 2012/2013
  • 58. Caveats Real time vs. complexity CPU time vs. RAM vs. disk 58 Tecniche di programmazione A.A. 2012/2013
  • 59. Caveats Real time vs. complexity CPU time vs. RAM vs. disk Worse, Average or Best Case? 59 Tecniche di programmazione A.A. 2012/2013
  • 60. Worse, Average or Best Case? 60
  • 61. Worse, Average or Best Case? Depends on input problem instance type 61
  • 70. Evaluate the complexity Linear search? 70 Tecniche di programmazione A.A. 2012/2013
  • 71. Evaluate the complexity Linear search O(n) Dichotomic search 71 Tecniche di programmazione A.A. 2012/2013
  • 72. Evaluate the complexity Linear search O(n) Dichotomic search O(log(n)) 72 Tecniche di programmazione A.A. 2012/2013
  • 74. ArrayList vs. LinkedList ArrayList LinkedList add(element) remove(object) get(index) set(index, element) add(index, element) remove(index) contains(object) indexOf(object) 74 Tecniche di programmazione A.A. 2012/2013
  • 75. ArrayList vs. LinkedList ArrayList LinkedList add(element) O(1) O(1) remove(object) O(n) + O(n) O(n) + O(1) get(index) O(1) O(n) set(index, element) O(1) O(n) + O(1) add(index, element) O(1) + O(n) O(n) + O(1) remove(index) O(n) O(n) + O(1) contains(object) O(n) O(n) indexOf(object) O(n) O(n) 75 Tecniche di programmazione A.A. 2012/2013
  • 76. In theory, there is no difference between theory and practice. 76 Tecniche di programmazione A.A. 2012/2013
  • 77. Licenza d’uso Queste diapositive sono distribuite con licenza Creative Commons “Attribuzione - Non commerciale - Condividi allo stesso modo (CC BY-NC-SA)” Sei libero: di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico, rappresentare, eseguire e recitare quest'opera di modificare quest'opera Alle seguenti condizioni: Attribuzione — Devi attribuire la paternità dell'opera agli autori originali e in modo tale da non suggerire che essi avallino te o il modo in cui tu usi l'opera. Non commerciale — Non puoi usare quest'opera per fini commerciali. Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una licenza identica o equivalente a questa. http://creativecommons.org/licenses/by-nc-sa/3.0/ 77 Tecniche di programmazione A.A. 2012/2013