This document discusses analyzing algorithms and their running time. It begins by introducing key topics in analyzing algorithms like big-O notation and generalizing running time. It then provides examples of using big-O notation to determine the time complexity of simple algorithms and functions. The document explains that big-O notation allows algorithms to be compared and classified based on how their running time grows relative to the input size.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
61 views
Analysis of Algorithms: The Non-Recursive Case
This document discusses analyzing algorithms and their running time. It begins by introducing key topics in analyzing algorithms like big-O notation and generalizing running time. It then provides examples of using big-O notation to determine the time complexity of simple algorithms and functions. The document explains that big-O notation allows algorithms to be compared and classified based on how their running time grows relative to the input size.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29
Analysis of Algorithms
The Non-recursive Case
Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License. Key Topics: Introduction Generalizing Running Time Doing a Timing Analysis Big-Oh Notation Big-Oh Operations Analyzing Some Simple Programs no Subprogram calls Worst-Case and Average Case Analysis Analyzing Programs with Non-Recursive Subprogram Calls Classes of Problems
Why Analyze Algorithms? An algorithm can be analyzed in terms of time efficiency or space utilization. We will consider only the former right now. The running time of an algorithm is influenced by several factors:
Speed of the machine running the program Language in which the program was written. For example, programs written in assembly language generally run faster than those written in C or C++, which in turn tend to run faster than those written in Java. Efficiency of the compiler that created the program The size of the input: processing 1000 records will take more time than processing 10 records. Organization of the input: if the item we are searching for is at the top of the list, it will take less time to find it than if it is at the bottom.
Generalizing Running Time
Input Size: n (1) log n n n log n n
n
2
5 1 3 5 15 25 125 32 10 1 4 10 33 100 10
10
100 1 7 100 664 10 4
10 6 10 30
1000 1 10 1000 10 4 10 6 10 9 10 300
10000 1 13 10000 10 5 10 8 10 12 10 3000
Al comparar el crecimiento de el tiempo de ejecucincomo la entrada crece con el crecimiento de las funciones conocidas. Analyzing Running Time 1. n = read input from user 2. sum = 0 3. i = 0 4. while i < n 5. number = read input from user 6. sum = sum + number 7. i = i + 1 8. mean = sum / n T (n), o el tiempo de ejecucin de un algoritmo concreto en la entrada de tamao n, se considera el nmero de veces que las instrucciones en el algoritmo se ejecuta. Algoritmo pseudo cdigo ilustra el clculo de la media (promedio) de un conjunto de n nmeros: Statement Number of times executed 1 1 2 1 3 1 4 n+1 5 n 6 n 7 n 8 1 El tiempo de clculo para este algoritmo en trminosde tamao de entrada n es: T (n) = 4n + 5. Big-Oh Notation Definicin 1: Sea f (n) yg (n) dos funciones.Escribimos: f (n) = O (g (n)) o f = O (g) (se lee "f de n es grande de g de n" o "f es grande de g") si no es un entero positivo C tal que f (n) <= C * g(n) para todo entero positivo n . La idea bsica de las grandes-Oh notacin es la siguiente: Supongamos que f y g son las funciones reales de una variable real x. Si, para valores grandes de x, la grfica de f est ms cerca del eje horizontalde la grfica de un mltiplo de g, entonces f es de orden g, es decir, f (x) = O (g (x)). Por lo tanto, g (x)representa una cota superior de f (x). Example 1 Supongamos que f (n) = 5n y g (n) = n. Para demostrar que f = O (g), tenemos que demostrar la existencia de una constante C que figura en la definicin 1. Es evidente que 5 es un f tan constante (n) = 5 * g (n). Podramos elegir una C grande como el 6, porque la definicin establece que f (n) debe ser menor o igual aC * g (n), pero por lo general tratar de encontrar la ms pequea. Por lo tanto, existe una constante C (slo tenemosuno) y f = O (g). Example 2 En el anlisis de la medicin anterior, que termin conT (n) = 4n + 5, y llegamos a la conclusin intuitiva que T(n) = O (n) porque el tiempo de ejecucin crece linealmente a medida que n crece. Ahora, sin embargo, podemos demostrar matemticamente:
Para demostrar que f (n) = 4n + 5 = O (n), tenemos que producir una constante C tal que: f (n) <= C * n para todo n.
Si tratamos de C = 4, esto no funciona porque 4n + 5no es menor que 4n. Necesitamos C, al menos, nuevepara cubrir todas las n. Si n = 1, C tiene que ser 9, pero C puede ser menor para valores mayores de n (sin = 100, C puede ser 5). Desde la C elegido debe trabajar para todo n, tenemos que usar 9:
4n + 5 <= 4n + 5n = 9n
Como nos han producido una constante C que funciona para todo n, podemos concluir :
T(4v + 5) = O(v)
Example 3 Por ejemplo f (n) = n2: Vamos a probar que f (n) O (n).
Para ello, tenemos que demostrar que no puede existir una constante C que satisfaga la definicin de grandes Oh. Vamos a probar esto por la contradiccin. Supongamos que existe una constante C que funciona, y luego, por la definicin de las grandes-Oh:n2 <= C * n para todo n. Supongamos que n es cualquier nmero real positivomayor que C, entonces: n * n> C * n, o n2> C * n.
Por lo tanto, existe un nmero real n tal que n2> C * n. Esto contradice la suposicin, por lo que la suposicin es falsa. No hay aire que puede funcionar para todo n: f(n) = O(n) when f(n) = n2
Example 4 Supongamos que f (n) = n2 + 3n - 1. Queremos demostrar que f (n) = O (n2). f (n) = n2 + 3n - 1 <N2 + 3n (sustraccin hace las cosas ms pequeas por lo que soltar) <= N2 + 3N2 (desde el n <= n2para todo n enteros) = 4N2
Por lo tanto, si C = 4, hemos demostrado que f (n) = O (n2). Tenga en cuenta que lo nico que hacemos es encontrar una funcin simple que es un lmite superior de la funcin original. Debido a esto, tambin podramos decir que
Esta sera una descripcin mucho ms dbil, pero sigue siendo vlido. f (n) = O (n3), ya que (n3) es un lmite superior en n2 Example 5 Show: f(n) = 2n 7 - 6n 5 + 10n 2 5 = O(n 7 ) f(n) < 2n 7 + 6n 5 + 10n 2 <= 2n 7 + 6n 7 + 10n 7 = 18n 7
thus, with C = 18 and we have shown that f(n) = O(n 7 ) Cualquier polinomio es grande-Oh de su mandato dems alto grado. Estamos tambin haciendo caso omiso de las constantes. Cualquier polinomio(incluyendo uno de carcter general) pueden ser manipulados para satisfacer la definicin de grandesOh haciendo lo que hicimos en el ltimo ejemplo: tomar el valor absoluto de cada coeficiente (esto slo puede aumentar la funcin), y luego ya
podemos cambiar los exponentes de todas las condiciones para el ms alto grado (la funcin originaldebe ser inferior a este tambin). Por ltimo, aadimosestos trminos en conjunto para obtener la mayorconstante C tenemos que encontrar una funcin quees un lmite superior a la original. n j <= n d if j <= d
Ajuste de la definicin de las grandes-Oh: Muchos algoritmos tienen una tasa de crecimiento que coincide con las funciones logartmicas. Hay que recordar quelog2 n es el nmero de veces que tenemos que dividirn por 2 para obtener una, o alternativamente, el nmero de dos de nosotros debemos multiplicar juntos para n:
n = 2 k log 2 n = k
Muchos "divide y vencers" algoritmos resolver un problema dividindolo en dos problemas ms pequeos. Que se siguen dividiendo hasta llegar al punto en que la solucin del problema es trivial. Esta constante divisin por 2 sugiere un tiempo logartmico en funcionamiento.
Definicin 2: Sea f (n) yg (n) dos funciones.Escribimos: f (n) = O (g (n)) o f = O (g) si son positivos enteros C y N tal que f (n) <= C * g (n)para todo n> = N.
Usando esta definicin ms general para los grandes-Oh, ahora podemos decir que si tenemos f (n) = 1, entonces f (n) = O (log (n)), ya que C = 1 y N = 2 va a funcionar. Con esta definicin, podemos ver claramente la diferencia entre los tres tipos de notacin : En los tres grficos anteriores, n0 es el valor mnimoposible para obtener los lmites vlidos, pero cualquier valor mayor trabajo Hay un teorema muy til que se relaciona con estas notaciones : Teorema: Para cualquier par de funciones f (n) yg (n), f(n) = (g (n)) si y slo si f (n) = O (g (n)) y f (n) = (g(n)). Example 6: Show: f(n) = 3n 3 + 3n - 1 = O (n 3 )
Tal como se deduce por el teorema anterior, para mostrar este resultado, tenemos que demostrar dos propiedades: f(n) = O (n 3 ) f(n) = O (n 3 )
En primer lugar, mostrar (i), utilizando las mismas tcnicas que ya hemos visto para los grandes-Oh. Consideramos N = 1, y por lo tanto slo se consideran n> = 1 para mostrar el resultado de grandes Oh. f(n) = 3n 3 + 3n - 1 < 3n 3 + 3n + 1 <= 3n 3 + 3n 3 + 1n 3 = 7n 3
por lo tanto, con C = 7 and N = 1 hemos demostrado que f(n) = O(n 3 ) A continuacin, se muestra (ii). Debemos tratar de daruna cota inferior de f (n). En este caso, elegimos un valor de N, de modo que el trmino de mayor orden en el f (n) siempre dominar (mayor que) los trminos de orden inferior.
Elegimos N = 2, ya que para n> = 2, tenemos n3> = 8.Esto permitir que n3 a ser mayor que el resto del polinomio (3n - 1) para todo n> = 2.
Por lo tanto, al restar un trmino n3 adicionales, seforma un polinomio que siempre ser menor que f (n)para n> = 2. f(n) = 3n 3 + 3n - 1 > 3n 3 - n3 since n 3 > 3n - 1 for any n >= 2 = 2n 3 Por lo tanto, con C = 2 y N = 2, hemos demostrado que f(n) = O (n 3 )
ya que f (n) se demuestra que es siempre mayor que 2n 3 . Big-Oh Operations Summation Rule Suppose T1(n) = O(f1(n)) and T2(n) = O(f2(n)). Further, suppose that f2 grows no faster than f1, i.e., f2(n) = O(f1(n)). Then, we can conclude that T1(n) + T2(n) = O(f1(n)). More generally, the summation rule tells us O(f1(n) + f2(n)) = O(max(f1(n), f2(n))). Proof:
Suppose that C and C' are constants such that T1(n) <= C * f1(n) and T2(n) <= C' * f2(n). Let D = the larger of C and C'. Then,
T1(n) + T2(n) <= C * f1(n) + C' * f2(n) <= D * f1(n) + D * f2(n) <= D * (f1(n) + f2(n)) <= O(f1(n) + f2(n)) Regla del producto Supongamos que T1 (n) = O (f1 (n)) y T2 (n) = O (f2(n)). Entonces, podemos concluir que T1 (n) * T2 (n) = O (f1 (n) * f2 (n)). La regla del producto se puede probar usando una estrategia similar a la prueba de regla de la suma. Analizar algunos programas sencillos (con llamadas No Sub-programa)
Reglas Generales:
Todos los enunciados bsicos (asignaciones, lee, escribe, prueba condicional, llamadas a la biblioteca)se ejecutan en tiempo constante: O (1).
El tiempo para ejecutar un bucle es la suma, en todo momento alrededor del circuito, el tiempo para ejecutar todas las sentencias en el bucle, ms el tiempo para evaluar la condicin de terminacin. Evaluacin de las condiciones de terminacin bsica es O (1) en cada iteracin del bucle.
La complejidad de un algoritmo est determinada por la complejidad de las afirmaciones ms frecuentemente ejecutadas. Si un conjunto de estados tienen un tiempo de ejecucin de O (n3) y el resto es O (n), entonces la complejidad del algoritmo es O (n3).Este es el resultado de la regla de adicin. Example 7
Calcular el tiempo de las grandes Oh funcionamiento de los siguientes C + + segmento de cdigo:
for (i = 2; i <n; i + +) { suma + = i; }
El nmero de iteraciones de un bucle es igual al ndice de la parte superior del bucle menos el ndice de fondo, adems de una instruccin ms para tener en cuentala prueba condicional final. Nota: si la condicin del bucle de terminacin es i <= n, en lugar de i <n, entonces el nmero de veces que se realiza la prueba condicional es:
((top_index + 1) - bottom_index) + 1)
En este caso, tenemos que n - 2 + 1 = n - 1. La asignacin en el bucle se ejecuta n - 2 veces. Por lo tanto, tenemos que (n - 1) + (n - 2) = (2n - 3)instrucciones ejecutadas = O (n). Example 8 Considere el algoritmo de ordenacin se muestra a continuacin. Encontrar el nmero de instrucciones ejecutadas y la complejidad de este algoritmo. 1) for (i = 1; i < n; i++) { 2) SmallPos = i; 3) Smallest = Array[SmallPos]; 4) for (j = i+1; j <= n; j++) 5) if (Array[j] < Smallest) { 6) SmallPos = j; 7) Smallest = Array[SmallPos] } 8) Array[SmallPos] = Array[i]; 9) Array[i] = Smallest; } El tiempo de clculo total es: T(n) = (n) + 4(n-1) + n(n+1)/2 1 + 3[n(n-1) / 2] = n + 4n - 4 + (n 2 + n)/2 1 + (3n 2 - 3n) / 2 = 5n - 5 + (4n 2 - 2n) / 2 = 5n - 5 + 2n 2 - n = 2n 2 + 4n - 5 = O(n 2 ) Example 9 Cul es la complejidad de estecdigo en C + +? 1) cin >> n; // Same as: n = GetInteger(); 2) for (i = 1; i <= n; i ++) 3) for (j = 1; j <= n; j ++) 4) A[i][j] = 0; 5) for (i = 1; i <= n; i ++) 6) A[i][i] = 1; El siguiente fragmento de inicializa una matriz bidimensional A (que tiene n filas y n columnas) de una matriz identidad nxn - es decir, una matriz con 1 en la diagonal y 0 en cualquier otro lugar. Ms formalmente, si A es una matriz identidad de nxn, entonces:
A x M = M x A = M, para cualquier matriz n X n M. Example 10 Aqu es un simple algoritmo de bsqueda lineal que devuelve la ubicacin del ndice de un valor en una matriz. /* a is the array of size n we are searching through */ i = 0; while ((i < n) && (x != a[i])) i++; if (i < n) location = i; else location = -1; 1 + 3 + 5 + ... + (2n - 1) / n = (2 (1 + 2 + 3 + ... + n) - n) / n Sabemos que 1 + 2 + 3 + ... + N = n (n + 1) / 2, por lo que el nmero promedio de lneas de ejecutar es: [2[n(n+1)/2] n]/n =n =O(n) Nmero medio de lneas ejecutadasigual : Analyzing Programs with Non- Recursive Subprogram Calls While/repeat: add f(n) to the running time for each iteration. We then multiply that time by the number of iterations. For a while loop, we must add one additional f(n) for the final loop test.
For loop: if the function call is in the initialization of a for loop, add f(n) to the total running time of the loop. If the function call is the termination condition of the for loop, add f(n) for each iteration.
If statement: add f(n) to the running time of the statement.
int a, n, x; int bar(int x, int n) { int i; 1) for (i = 1; i < n; i++) 2) x = x + i; 3) return x; }
int foo(int x, int n) { int i; 4) for (i = 1; i <= n; i++) 5) x = x + bar(i, n); 6) return x; }
void main(void) { 7) n = GetInteger(); 8) a = 0; 9) x = foo(a, n) 10) printf("%d", bar(a, n)) } Here is the body of a function:
sum = 0; for (i = 1; i <= f(n); i++) sum += i;
where f(n) is a function call. Give a big-oh upper bound on this function if the running time of f(n) is O(n), and the value of f(n) is n!: Classes of Problems 1. Snickers Bar 200 calories 100 grams 2. Diet Coke 1 calorie 200 grams ... 200. Dry Spaghetti 500 calories 450 grams
Problems, Problems, Problems Different sets of problems: Intractable/Exponential: Problems requiring exponential time Polynomial: Problems for which sub-linear, linear or polynomial solutions exist NP-Complete: No polynomial solution has been found, although exponential solutions exist NP-Complete?
Polynomial Exponential Undecidable Two Famous Problems 1. Satisfiability Is: (a) ^ (b v c) ^ (~c v ~a) satisfiable? Is: (a) ^ (b v c) ^ (~c v ~a) ^ (~b) satisfiable?
2. Knapsack
n E (ai * vi) = T i = 1 Polynomial Transformation Informally, if P 1 P 2 , then we can think of a solution to P 1 being obtained from a solution to P 2 in polynomial time. The code below gives some idea of what is implied when we say P 1
P 2 : Convert_To_P2 p1 = ... /* Takes an instance of p1 and converts it to an instance of P2 in polynomial time. */ Solve_P2 p2 = ... /* Solves problem P2 */
Solve_P1 p1 = Solve_P2(Convert_To_P2 p1); Given the above definition of a transformation, these theorems should not be very surprising: If H 1 H 2 then H 2 e P H 1 e P If H 1 H 2 then H 2 e P H 1 e P These theorems suggest a technique for proving that a given problem H is NP- complete.
To Prove H e NP:
1) Find a known NP-complete problem H NP 2) Find a transformation such that H NP H 3) Prove that the transformation is polynomial.
The meaning of NP-Completeness A Statement of a Problem: Solving a problem means finding one algorithm that will solve all instances of the problem. H e NH, H EAT
(Ebook) Data-driven design and construction : 25 strategies for capturing, analyzing and applying building data by Deutsch, Randy ISBN 9781118898703, 9781118899212, 9781118899267, 9781119149682, 1118898702, 1118899210, 1118899261, 1119149681 download