java - Building a summation from analyzing code? -
i have midterm tomorrow, , supposed able analyze code. thing don't understand @ all. given this:
consider java method comparing 2 strings. method has 2 inputs , should use 2 variables express running time. let
n
length ofa
, letm
length ofb
. can express running time function ofn
and/orm
. if assume without loss of generalityn < m
.private static int comparestrings ( string , string b) { int = 0; while ( < . length () && < b. length ( ) ) { if (a . charat ( ) < b. charat ( ) ) return −1; if (a . charat ( ) > b. charat ( ) ) return 1; ++; } if (a . length () < b. length ( ) ) return −1; if (a . length () > b. length ( ) ) return 1; }
a) express worst case running time of method sum.
b) simplify sum , state big-oh bound.
the notation need in :
n Σ i= 1
i don't understand how build sum out of code, or it's running time. step step instructions great. problem given practice problem , not homework. want understand this!!!
the worst case run time o(n).
why?
1. because assume n < m , algorithm compares characters long there characters remaining in both strings [characters yet compared].
naturally condition fails hold when there no more characters in shortest string, a.
- because worst case must occur when while loop not interrupted return.
this can coincide case in evaluate n times.
the stipulation a substring of b such a[0] == b[0] also.
cost sum of
- evaluating while condition
- the cost of 2 comparisons, etc. in body of loop
- incrementing i
it bounded above nc + k c worst case cost of while loop body, k cost of operations evaluated once (such return statement), , n has agreed-upon significance.
if allow n rise without bound can see fits definition of o(n).
Comments
Post a Comment