Docsity

Algorithms and Complexity, Lecture Notes - Computer Science, Study notes of Algorithms and Programming

Partial preview of the text

Download Algorithms and Complexity, Lecture Notes - Computer Science and more Study notes Algorithms and Programming in PDF only on Docsity!

Algorithms and Complexity

Zeph Grunschlag

Agenda

Section 2.1: Algorithms

 Pseudocode

 Recursive Algorithms (Section 3.4)

Section 2.2: Complexity of Algorithms

Section 1.8: Growth of Functions

 Big-O

 Big- (Omega)

 Big- (Theta)

Pseudo-Java

Possible alternative to text’s pseudo-Java

Start with ―real‖ Java and simplify:

int f(int[] a){

int x = a[0];

for(int i=1; i<a.length; i++){

if(x > a[i])

x = a[i];

return x;

Pseudo-Java

Version 1

integer f(integer_array (a 1 , a 2 , …, a n) ){

x = a 1

for(i =2 to n){

if(x > a i)

x = a i

return x

L8 7

Algorithm for Surjectivity

boolean isOnto( function f: (1, 2,…, n)  (1, 2,…, m) ){

if( m > n ) return false // can’t be onto

soFarIsOnto = true

for( j = 1 to m ){

soFarIsOnto = false

for(i = 1 to n ){ if ( f(i ) == j )

soFarIsOnto = true

if( !soFarIsOnto ) return false;

return true;

Improved Algorithm for

Surjectivity

boolean isOntoB( function f: (1, 2,…, n)  (1, 2,…, m) ){

if( m > n ) return false // can’t be onto for( j = 1 to m ) beenHit[ j ] = false; // does f ever output j? for(i = 1 to n ) beenHit[ f(i ) ] = true; for(j = 1 to m ) if( !beenHit[ j ] )

return false;

return true;

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

Compute 5!

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(5)= 5·f(4)

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(3)= 3·f(2)

f(4)= 4·f(3)

f(5)= 5·f(4)

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(2)= 2·f(1)

f(3)= 3·f(2)

f(4)= 4·f(3)

f(5)= 5·f(4)

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(0)= 1 

f(1)= 1·f(0)

f(2)= 2·f(1)

f(3)= 3·f(2)

f(4)= 4·f(3)

f(5)= 5·f(4)

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(2)= 2·f(1)

f(3)= 3·f(2)

f(4)= 4·f(3)

f(5)= 5·f(4)

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(4)= 4·f(3)

f(5)= 5·f(4)

Recursive Algorithms

long factorial(int n){

if (n<=0) return 1; return nfactorial(n-1);*

}

f(5)= 5·f(4)