1 / 9

Program Efficiency

Program Efficiency. Interested in “order of magnitude” That is, how the work grows as n grows Where n is the “problem size” Usually we just look at the loops Since that’s where most work occurs Big-O notation O(f( n )) means work grows like about f( n ) Constants don’t matter.

hong
Download Presentation

Program Efficiency

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Program Efficiency • Interested in “order of magnitude” • That is, how the work grows as n grows • Where n is the “problem size” • Usually we just look at the loops • Since that’s where most work occurs • Big-O notation • O(f(n)) means work grows like about f(n) • Constants don’t matter

  2. Big-O Example 1 for(int i = 0; i < x.length; i++) { no loops here } • We say this is O(n) • Since it takes about x.length “work” • Depends on problem “size” • Size is always given as n

  3. Big-O Example 2 for(int i = 0; i < x.length; i++) { for(int j = 0; j < x.length; j++) { no loops here } } • It’s n “work” for each of n times thru outer loop • So, this is O(n2)

  4. Big-O Example 3 for(int i = 0; i < x.length; i++) { for(int j = i + 1; j < x.length; j++) { no loops here } } • When i = 0, we have n - 1 “work” • When i = 1, we have n - 2 “work”, etc. • So, (n - 1)+(n-2)+ … + 1 = n(n-1)/2, or O(n2)

  5. Program Efficiency • Big-O notation • O(1) constant time • O(n) linear time • O(n log n) log linear • O(n2) quadratic • O(n3) cubic • O(2n) exponential • O(n!) factorial • Polynomials are good, exponentiala are bad

  6. Big-O Example 4 for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { for(int k = n; k >= 1; k--) { no loops here } } } • n  n n “work”, so this is O(n3)

  7. Big-O Example 5 for(int i = 0; i <= n; i++) { for(int j = 0; j < i * i; j++) { no loops here } } • 02 + 12 + 22 + … + n2 = n(n+1)(2n+1)/6 • So, O(n3)

  8. Big-O Example 6 for(int i = n; i >= 0; i -= 2) { no loops here } • About n/2 iterations • So, O(n)

  9. Big-O Example 7 for(int i = 0; i < n; i++) { for(int j = i; j > 0; j /= 2) { no loops here } } • 0 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + … + log n + log n • Adds up to about (log n)((log n) + 1) • Where “log” is to the base 2 • This is O((log n)2)

More Related