cs201: part 1

64
CS201: PART 1 Data Structures & Algorithms S. Kondakcı

Upload: ulysses-watkins

Post on 03-Jan-2016

38 views

Category:

Documents


6 download

DESCRIPTION

CS201: PART 1. Data Structures & Algorithms S. Kondakcı. Analysis of Algorithms. Algorithm. Input. Output. An algorithm is a step-by-step procedure for solving a problem in a finite amount of time. Theoretical Analysis of Algorithms: - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS201: PART 1

CS201: PART 1

Data Structures & AlgorithmsS. Kondakcı

Page 2: CS201: PART 1

Analysis of Algorithms 2

Analysis of Algorithms

AlgorithmInput Output

An algorithm is a step-by-step procedure for

solving a problem in a finite amount of time.

Theoretical Analysis of Algorithms:

•Uses a high-level description of the algorithm instead of an implementation

•Characterizes running time as a function of the input size n.

•Takes into account all possible inputs Allows us to evaluate the speed of any design independent of its implementation.

Page 3: CS201: PART 1

Analysis of Algorithms 3

Program Efficiency

Program efficiency: is a measure of the amount of resources required to produce desired results.

Efficiency Aspects:

1) What are the important resources we should try to optimize?

2) Where are the important efficiency gains to be made?3) How important is efficiency in the first place?

Page 4: CS201: PART 1

Analysis of Algorithms 4

Efficiency Today

User Efficiency. The amount of time and effort users will spend to learn how o use the program, how to prepare the data, how to configure and customize the program, and how to interpret and use the output.Maintenance Efficiency. The amount of time and effort maintenance group will spend reading a program and its technical documentation in order to understand it well enough to make any necessary modifications. Algorithmic Complexity. The inherent efficiency of the method itself, regardless of which machine we run it on or how we code it. Coding Efficiency. This is the traditional efficiency measure. Here we are concerned with how much processor time and memory space a computer program requires to produce desired results. Coding efficiency is the key step towards optimal usage of machine resources.

Page 5: CS201: PART 1

Analysis of Algorithms 5

Programmer’s Duty

Programmers should should keep these in mind:

1. Correct, robust, and reliable.2. Easy to use for its intended end-user

group.3. Easy to understand and easy to modify. 4. Portable.5. Consistency in Input/Output behavior.6. User documentation.

Page 6: CS201: PART 1

Analysis of Algorithms 6

Optimization

Optimization on CPU-Time: Consider a network security assessment tool as a real-time application. The application works like a security scanner protocol designed to audit, monitor, and correct all aspects of network security. Real-time processing of the intercepted network packets containing inspection information requires faster data processing. Besides, such a process should generate some auditing information.Optimization on Memory: Developing programs that do not fit into the memory space available on your systems is often quite a bit demanding. Kernel level processing of the network packets requires kernel memory optimization and a powerful and failsafe memory management capability.Providing Run-time Continuity: Extensive machine-level optimization is a major requirement for continuously running programs, such as the security scanner daemons.Reliability and Correctness: One of the inevitable efficiency requirements is the absolute reliability. The second important efficiency factor is correctness. That is, your program should do exactly what it is supposed to do. Choosing and implementing a reliable inspection methodology should be done with precision.Optimization on Programmer’s Time: How efficient a programmer works depends on the choice of team policy and developmen tool selection.

Page 7: CS201: PART 1

Analysis of Algorithms 7

Coding Efficiency: Unstructured Code

8: read(x,y,z); if (x >= y) goto 1; if (y >= z) goto 5; goto 4;1: if (x >= z) goto 2; goto 4;5: big = y; goto 3;2: big = x; goto 3;4: big = z;3: if (!eof) goto 8

Figure 5.2: Unstructured coding, see Figure 5.3 /Efficient Programming/S. Kondakci-1999

Page 8: CS201: PART 1

Analysis of Algorithms 8

Coding Efficiency: Structured Code

while (!eof) {read(x,y,z);if ((x >= y) && (x >= z)) big = x;else if ((y >= x) && (y >= z)) big = yelse big = z;

}

Figure 5.3: Structured coding versus unstructured coding /Efficient Programming/S. Kondakci-1999

Page 9: CS201: PART 1

Analysis of Algorithms 9

Protecting Against Run-time Errors

Illegal pointer operations.Array subscript out of bound.Endless loops may cause stacks grow into the heap area.Presentational errors, such as network byte order, number conversions, division by zero, undefined results, e.g., tan(90) = undefined.Trying to write over the kernel’s text area, or the data area.Referencing objects declared as prototype but not defined. Performing operations on a pointer pointing at NULL.Operating system weaknesses.

Page 10: CS201: PART 1

Analysis of Algorithms 10

Assertions A general pitfall: making assumptions that turn out not to be justified.

Most of the mistakes arise from simply misunderstanding the interaction between various pieces of code

The assertion rule states that you should always express yourself boldly or forcefully of the fact that there are some other things that you have not covered clear enough yet. Any assumptions you make in writing your programs should be documented somewhere in the code itself, particularly if you know or expect the assumption to be false in other environments.

Page 11: CS201: PART 1

Analysis of Algorithms 11

Does the Machine Understand Your Assumptions? Remember those assumptions are yours: They should be presented to the machine by any means that you are supposed to provide in your code. The machine will not be able to check your assumptions. This is simply a matter of including explicit checks in your code, even for things that “cannot happen”.

if (p == NULL)panic(“Driver routine: p is NULL\n”);

if (p->p_flags & BUSY); /* Safe to continue */…<etcetera> ASSERT(p !=NULL); If (p->p_flags & BUSY); /* Safe to continue */…<etcetera> …

Page 12: CS201: PART 1

Analysis of Algorithms 12

Guidelines for the implementation

1. Protect input parameters using call-by-value.2. Avoid global variables and functions with side effects.3. Make all temporary variables local to functions where they

are used.4. Never halt or sleep in a function. Spawn a dedicated function

if necessary.5. Avoid producing output within a function unless the sole

purpose of the function is output.6. Where appropriate use return values to return the status of

function calls.7. Avoid confusing programming tricks.8. Always strive for simplicity and clarity. Never sacrifice clarity

of expression for cleverness of expression.9. If any keep your assertions local to your code.10. Never sacrifice clarity of expression for minor reductions in

execution time.

Page 13: CS201: PART 1

Analysis of Algorithms 13

Debugging and TracingMaking use of the preprocessor can allow you to incorporate many debugging aids in your module, for instance, the driver module. Later, in the production version these debugging aids can be removed.

#ifdef DEBUG#define TRACE_OPEN (debugging && 0x01)#define TRACE_CLOSE (debugging && 0x02)#define TRACE_READ (debugging && 0x04)#define TRACE_WRITE (debugging && 0x08)

int debugging = -1; /* enable all traces output */#else#define TRACE_OPEN 0#define TRACE_CLOSE 0#define TRACE_READ 0#define TRACE_WRITE 0#endif...

Page 14: CS201: PART 1

Analysis of Algorithms 14

Tracing: Later in the Program

if (TRACE_READ)printf(‘’Device driver read, Packet number (%d) \n’’,pack_no);… <etcetera>…

Later, in the code the output of the trace information can be done by a manner similar to this:

Page 15: CS201: PART 1

Analysis of Algorithms 15

Checking Programs With lint (Unix)The lint utility is intended to verify some facets of a C program, such as its potential portability. lint derives from the idea of picking the “fluff” out of a C program. It does this, by advising on C constructs (including functions) and usage which might turn out to be ‘bugs’, portability problems, inconsistent declarations, bad function and argument types, or dead code. See the manual section lint(1) for further explanations.

$ cat mytest.cmain() /* nonsense */{

char y = ‘1’, z;int x = ‘p’;extern float duble();

goto LABEL1;while (1 !=0) {

LABEL1: x+= (long) y;printf(“Fasten your seat belts! %d\n”, x);}

return (y);}

Page 16: CS201: PART 1

Analysis of Algorithms 16

Now, Lint’ing$ lint –hxa mytest.c

 

(8) warning: loop not entered at top

(8) warning: constant in conditional context

 

variable unused in function

(3) z in main

 

implicitly declared to return int

(10) printf

 

declaration unused in block

(5) duble

 

function returns value, which is always ignored

printf

$ cat mytest.cmain() /* nonsense */{

char y = ‘1’, z;int x = ‘p’;extern float duble();

goto LABEL1;while (1 !=0) {

LABEL1: x+= (long) y;printf(“Fasten your seat belts! %d\n”, x);}

return (y);}

Page 17: CS201: PART 1

Analysis of Algorithms 17

Test Coverage Analysis Yet another tool born for execution tracing and analysis of programs called tcov,it can be used to trace and analyze a source code to report a coverage test. tcov does this by analysing the source code step-by-step. The extra code is generated by giving the –xa option to the compiler command, i.e.,

  $ gcc -xa -o src src.c

The –xa option invokes a runtime recording mechanism that creates a .d file for every .c file. The .d file accumulates execution data for the corresponding source file.

The tcov utility can then be run on the source file to generate statistics about the program. The following example source file, getmygid.c, is analysed as:

 $ cc -xa -o getmygid getmygid.c

$ tcov -a getmygid.c

$ ls –l getmy???*

-rwxr-xr-x 1 staff 25120 Feb 11 12:07 getmygid

-rw------- 1 staff 519 Sep 9 1994 getmygid.c

-rw-r--r-- 1 staff 9 Feb 11 12:07 getmygid.d

-rw-r--r-- 1 staff 1025 Feb 11 12:08 getmygid.tcov

Page 18: CS201: PART 1

Analysis of Algorithms 18

Example: getmygid.c $ cat getmygid.c #include <stdio.h>char *msg = "I am sorry I cannot tell you everything" ;int gid,egid;int uid,euid, pid ,ppid, i;int main(){ gid = getgid(); if (gid >= 0) printf("1- My GID is: %d\n", gid); egid = getegid(); if (egid >=0 ) printf("2- My EGID is: %d\n", egid); uid = getuid(); if ( uid >=0) printf("3- My uid is: %d\n", uid); euid = geteuid(); if (euid >= 0) printf("4- My Euid is: %d\n", euid); pid = getpid(); if ( pid >=0 ) printf("5- My pid is: %d\n", pid); ppid = getppid(); if ( ppid >= 0) printf("6- My ppid is: %d\n", ppid); prt_msg("We came to end!!!"); return 0; prt_msg(msg);}prt_msg(char *mesg){ printf("%s \n", mesg);}

Page 19: CS201: PART 1

Analysis of Algorithms 19

Tcov’ing getmygid.c $ cat getmygid.tcov  ##### -> #include <stdio.h> ##### -> char *msg = "I am sorry I cannot tell you everything" ; ##### -> ##### -> int gid,egid; ##### -> int uid,euid, pid ,ppid, i; ##### -> int main() ##### -> { 2 -> gid = getgid(); 2 -> if (gid >= 0) printf("1- My GID is: %d\n", gid); 2 -> egid = getegid(); 2 -> if (egid >=0 ) printf("2- My EGID is: %d\n", egid); 2 -> uid = getuid(); 2 -> if ( uid >=0) printf("3- My uid is: %d\n", uid); 2 -> euid = geteuid(); 2 -> if (euid >= 0) printf("4- My Euid is: %d\n", euid); 2 -> pid = getpid(); 2 -> if ( pid >=0 ) printf("5- My pid is: %d\n", pid); 2 -> ppid = getppid(); 2 -> if ( ppid >= 0) printf("6- My ppid is: %d\n", ppid); 2 -> prt_msg("We came to end!!!"); 2 -> return 0; 2 -> prt_msg(msg);

2 -> } 2 -> prt_msg(mesg) 2 -> char *mesg; 2 -> { 2 -> printf("%s \n", mesg); 2 -> }

Page 20: CS201: PART 1

Analysis of Algorithms 20

Tcov’ing getmygid.c

Top 10 Blocks  Line Count  9 2 11 2 13 2 15 2 17 2 19 2 21 2

29            2  8 Basic blocks in this file 8 Basic blocks executed 100.00 Percent of the file executed  16 Total basic block executions 2.00 Average executions per basic block

As shown, tcov(1) generates an annotated listing of the source file (getmygid.tcov), where each line is prefixed with a number indicating the count of execution of each statement on the line. Finally per line and per block statistics are shown.

Page 21: CS201: PART 1

Analysis of Algorithms 21

Have nice break!

Page 22: CS201: PART 1

Analysis of Algorithms

AlgorithmInput Output

An algorithm is a step-by-step procedure forsolving a problem in a finite amount of time.

Page 23: CS201: PART 1

Analysis of Algorithms 23

Running Time

Most algorithms transform input objects into output objects.The running time of an algorithm typically grows with the input size.Average case time is often difficult to determine.We focus on the worst case running time.

Easier to analyze Crucial to applications

such as games, finance and robotics

0

20

40

60

80

100

120

Runnin

g T

ime

1000 2000 3000 4000

Input Size

best caseaverage caseworst case

Page 24: CS201: PART 1

Analysis of Algorithms 24

Experimental Studies

Write a program implementing the algorithmRun the program with inputs of varying size and compositionUse a function, like the built-in clock() function, to get an accurate measure of the actual running timePlot the results

0

1000

2000

3000

4000

5000

6000

7000

8000

9000

0 50 100

Input Size

Tim

e (

ms)

Page 25: CS201: PART 1

Analysis of Algorithms 25

Limitations of Experiments

It is necessary to implement the algorithm, which may be difficultResults may not be indicative of the running time on other inputs not included in the experiment. In order to compare two algorithms, the same hardware and software environments must be used

Page 26: CS201: PART 1

Analysis of Algorithms 26

Theoretical Analysis

Uses a high-level description of the algorithm instead of an implementationCharacterizes running time as a function of the input size, n.Takes into account all possible inputsAllows us to evaluate the speed of an algorithm independent of the hardware/software environment

Page 27: CS201: PART 1

Analysis of Algorithms 27

Pseudocode

High-level description of an algorithmMore structured than English proseLess detailed than a programPreferred notation for describing algorithmsHides program design issues

Algorithm arrayMax(A, n)Input array A of n integersOutput maximum element of A

currentMax A[0]for i 1 to n 1 do

if A[i] currentMax thencurrentMax A[i]

return currentMax

Example: find max element of an array

Page 28: CS201: PART 1

Analysis of Algorithms 28

Pseudocode Details

Control flow if … then … [else …] while … do … repeat … until … for … do … Indentation replaces

braces Method declarationAlgorithm method (arg [, arg…])

Input …

Output …

Method/Function callmethod (arg [, arg…])

Return valuereturn expression

Expressions Assignment

(like in C++) Equality testing

(like in C++)n2 Superscripts and

other mathematical formatting allowed

Page 29: CS201: PART 1

Analysis of Algorithms 29

The Random Access Machine (RAM) Model

A CPU

A potentially unbounded bank of memory cells, each of which can hold an arbitrary number or character

01

2

Memory cells are numbered and accessing any cell in memory takes unit time.

Page 30: CS201: PART 1

Analysis of Algorithms 30

Primitive Operations

Basic computations performed by an algorithmIdentifiable in pseudocodeLargely independent from the programming languageExact definition not importantAssumed to take a constant amount of time in the RAM model

Examples: Evaluating an

expression Assigning a

value to a variable

Indexing into an array

Calling a method Returning from a

method

Page 31: CS201: PART 1

Analysis of Algorithms 31

Counting Primitive Operations

By inspecting the pseudocode, we can determine the maximum number of primitive operations executed by an algorithm, as a function of the input size

Algorithm arrayMax(A, n)

# operations

currentMax A[0] 2for i 1 to n 1 do 2 n

if A[i] currentMax then 2(n 1)currentMax A[i] 2(n 1)

{ increment counter i } 2(n 1)return currentMax 1

Total 7n 1

Page 32: CS201: PART 1

Analysis of Algorithms 32

Estimating Running Time

Algorithm arrayMax executes 7n 1 primitive operations in the worst case. Define:a = Time taken by the fastest primitive operationb = Time taken by the slowest primitive operation

Let T(n) be worst-case time of arrayMax. Thena a (7(7nn 1) 1) TT((nn)) bb(7(7nn 1) 1)

Hence, the running time T(n) is bounded by two linear functions

Page 33: CS201: PART 1

Analysis of Algorithms 33

Growth Rate of Running Time

Changing the hardware/ software environment Affects T(n) by a constant factor, but Does not alter the growth rate of T(n)

The linear growth rate of the running time T(n) is an intrinsic property of algorithm arrayMax

Page 34: CS201: PART 1

Analysis of Algorithms 34

Growth Rates

Growth rates of functions: Linear n Quadratic n2

Cubic n3

In a log-log chart, the slope of the line corresponds to the growth rate of the function

1E+01E+21E+41E+61E+8

1E+101E+121E+141E+161E+181E+201E+221E+241E+261E+281E+30

1E+0 1E+2 1E+4 1E+6 1E+8 1E+10n

T(n

)

Cubic

Quadratic

Linear

Page 35: CS201: PART 1

Analysis of Algorithms 35

Constant Factors

The growth rate is not affected by constant factors

or lower-order terms

Examples 102n 105 is a

linear function 105n2 108n is a

quadratic function

1E+01E+21E+41E+61E+8

1E+101E+121E+141E+161E+181E+201E+221E+241E+26

1E+0 1E+2 1E+4 1E+6 1E+8 1E+10n

T(n

)

Quadratic

Quadratic

Linear

Linear

Page 36: CS201: PART 1

Analysis of Algorithms 36

Big-Oh Notation

Given functions f(n) and g(n), we say that f(n) is O(g(n)) if there are positive constantsc and n0 such that

f(n) cg(n) for n n0

Example: 2n 10 is O(n) 2n 10 cn (c 2) n 10 n 10(c 2) Pick c 3 and n0 10

1

10

100

1,000

10,000

1 10 100 1,000n

3n

2n+10

n

Page 37: CS201: PART 1

Analysis of Algorithms 37

Big-Oh Example

Example: the function n2 is not O(n)

n2 cn n c The above

inequality cannot be satisfied since c must be a constant

1

10

100

1,000

10,000

100,000

1,000,000

1 10 100 1,000n

n^2

100n

10n

n

Page 38: CS201: PART 1

Analysis of Algorithms 38

More Big-Oh Examples

7n-2

7n-2 is O(n)need c > 0 and n0 1 such that 7n-2 c•n for n n0

this is true for c = 7 and n0 = 1

3n3 + 20n2 + 53n3 + 20n2 + 5 is O(n3)need c > 0 and n0 1 such that 3n3 + 20n2 + 5 c•n3 for n

n0

this is true for c = 4 and n0 = 21 3 log n + log log n3 log n + log log n is O(log n)need c > 0 and n0 1 such that 3 log n + log log n c•log n

for n n0

this is true for c = 4 and n0 = 2

Page 39: CS201: PART 1

Analysis of Algorithms 39

Big-Oh and Growth Rate

The big-Oh notation gives an upper bound on the growth rate of a functionThe statement “f(n) is O(g(n))” means that the growth rate of f(n) is no more than the growth rate of g(n)

We can use the big-Oh notation to rank functions according to their growth rate

f(n) is O(g(n)) g(n) is O(f(n))

g(n) grows more Yes No

f(n) grows more No Yes

Same growth Yes Yes

Page 40: CS201: PART 1

Analysis of Algorithms 40

Big-Oh Rules

If is f(n) a polynomial of degree d, then f(n) is O(nd), i.e.,

1. Drop lower-order terms2. Drop constant factors

Use the smallest possible class of functions

Say “2n is O(n)” instead of “2n is O(n2)”Use the simplest expression of the class

Say “3n 5 is O(n)” instead of “3n 5 is O(3n)”

Page 41: CS201: PART 1

Analysis of Algorithms 41

Asymptotic Algorithm Analysis

The asymptotic analysis of an algorithm determines the running time in big-Oh notationTo perform the asymptotic analysis

We find the worst-case number of primitive operations executed as a function of the input size

We express this function with big-Oh notationExample:

We determine that algorithm arrayMax executes at most 7n 1 primitive operations

We say that algorithm arrayMax “runs in O(n) time”Since constant factors and lower-order terms are eventually dropped anyhow, we can disregard them when counting primitive operations

Page 42: CS201: PART 1

Analysis of Algorithms 42

Computing Prefix Averages

We further illustrate asymptotic analysis with two algorithms for prefix averagesThe i-th prefix average of an array X is average of the first (i 1) elements of X:

AA[[ii]] XX[0] [0] XX[1] [1] … … XX[[ii])/(])/(ii+1)+1)0

5

10

15

20

25

30

35

1 2 3 4 5 6 7

X

A

Page 43: CS201: PART 1

Analysis of Algorithms 43

Prefix Averages (Quadratic)The following algorithm computes prefix averages in quadratic time by applying the definition

Algorithm prefixAverages1(X, n)Input array X of n integersOutput array A of prefix averages of X #operations A new array of n integers nfor i 0 to n 1 do n

s X[0] nfor j 1 to i do 1 2 … (n 1)

s s X[j] 1 2 … (n 1)A[i] s (i 1) n

return A 1

Page 44: CS201: PART 1

Analysis of Algorithms 44

Arithmetic Progression

The running time of prefixAverages1 isO(1 2 …n)

The sum of the first n integers is n(n 1) 2 There is a simple

visual proof of this fact

Thus, algorithm prefixAverages1 runs in O(n2) time

0

1

2

3

4

5

6

7

1 2 3 4 5 6

Page 45: CS201: PART 1

Analysis of Algorithms 45

Prefix Averages (Linear)The following algorithm computes prefix averages in linear time by keeping a running sum

Algorithm prefixAverages2(X, n)Input array X of n integersOutput array A of prefix averages of X #operationsA new array of n integers ns 0 1for i 0 to n 1 do n

s s X[i] nA[i] s (i 1) n

return A 1Algorithm prefixAverages2 runs in O(n) time

Page 46: CS201: PART 1

Analysis of Algorithms 46

Computing Spans

We show how to use a stack as an auxiliary data structure in an algorithmGiven an an array X, the span S[i] of X[i] is the maximum number of consecutive elements X[j] immediately preceding X[i] and such that X[j] X[i] Spans have applications to financial analysis

E.g., stock at 52-week high

6 3 4 5 2

1 1 2 3 1

X

S

01234567

0 1 2 3 4

Page 47: CS201: PART 1

Analysis of Algorithms 47

Quadratic Algorithm

Algorithm spans1(X, n)Input array X of n integersOutput array S of spans of X #S new array of n integers nfor i 0 to n 1 do n

s 1 nwhile s i X[i s] X[i] 1 2 … (n 1)

s s 1 1 2 … (n 1)S[i] s n

return S 1

Algorithm spans1 runs in O(n2) time

Page 48: CS201: PART 1

Analysis of Algorithms 48

Have nice break!

Page 49: CS201: PART 1

Analysis of Algorithms 49

RecursionRecursion = a function calls itself as a function for unknown times. We call this recursive call

1

1

n

i

sum i

for (i = 1 ; i <= n-1; i++)

sum = sum +1;

int sum(int n) {

if (n <= 1)

return 1

else

return (n + sum(n-1));

}

Page 50: CS201: PART 1

Analysis of Algorithms 50

Recursive function

int f( int x )

{

if( x == 0 )

return 0;

else

return 2 * f( x - 1 ) + x * x;

}

22 ( 1)f f x x

Page 51: CS201: PART 1

Analysis of Algorithms 51

RecursionCalculate factorial (n!) of a positive integer:

n! = n(n-1)(n-2)...(n-n-1), 0! = 1! = 1

0! 1, ! (( 1)!) ( 0)n n n n int factorial(int n) {

if (n <= 1)

return 1;

else

return (n * factorial(n-1));

}

Page 52: CS201: PART 1

Analysis of Algorithms 52

Fibonacci numbers, Bad algorith for n>40 !

long fib(int n) {

if (n <= 1)

return 1;

else

return fib(n-1) + fib(n-2);

}

0 1 2 3 4 1 2

1 1

1

1, 1, 2, 3, 5,...,

( 1) (5 / 3)

i i i

k k k

k

F F F F F F F F

F F F

T k

( ) (3 / 2)Nfib N

Page 53: CS201: PART 1

Analysis of Algorithms 53

Algorithm IterativeLinearSum(A,n)

Algorithm IterativeLinearSum(A,n):

Input: An integer array A and an integer n (size)

Output: The sum of the first n integers

if n = 1 then

return A[0]

else

while n 0 do

sum = sum + A[n]

n n - 1

return sum

Page 54: CS201: PART 1

Analysis of Algorithms 54

Algorithm LinearSum(A,n)

Algorithm LinearSum(A,n):

Input: An integer array A and an integer n (size)

Output: The sum of the first n integers

if n = 1 then

return A[0]

else

return LinearSum(A,n-1) + A[n-1]

Page 55: CS201: PART 1

Analysis of Algorithms 55

Iterative Approach: Algorithm IterativeReverseArray(A,i,n)

Algorithm IterativeReverseArray(A,i,n):

Input: An integer array A and an integers i and n

Output: The reversal of n integers in A starting at index i

while n > 1 do

swap A[i] and A[i+n-1]

i i +1

n n-2

return

Page 56: CS201: PART 1

Analysis of Algorithms 56

Algorithm ReverseArray(A,i,n)

Algorithm ReverseArray(A,i,n):

Input: An integer array A and an integers i and n

Output: The reversal of n integers in A starting at index i

if n > 1 then

swap A[i] and A[i+n-1]

call ReverseArray(A, i+1, n-2)

return

Page 57: CS201: PART 1

Analysis of Algorithms 57

Higher-Order Recursion

Algorithm BinarySum(A,i,n):

Input: An integer array A and an integers i and n

Output: The sum of n integers in A starting at index i

if n = 1 then

return A[i]

return BinarySum(A,i,[n/2])+BinarySum(A,i+[n/2],[n/2])

Making recursive calls more than a single call at a time.

Page 58: CS201: PART 1

Analysis of Algorithms 58

Kth Fibonacci Numbers0 1 1 2

0

1

2 1 0

3 2 1

4 3 2

5 4 3

6 5 4

7 6 5

8 7 6

0, 1, ,

1

1

1

1 1 1 1 3

1 3 1 1 5

1 5 3 1 9

1 9 5 1 15

1 15 9 1 25

1 25 15 1 41

1 41 25 1 67

i i iF F and F F F

For i

n

n

n n n

n n n

n n n

n n n

n n n

n n n

n n n

Page 59: CS201: PART 1

Analysis of Algorithms 59

Algorithm BinaryFib(k):

Input: An integer k

Output: A pair ( ) such that is the kth Fibonacci number and is the (k-1)st Fibonacci number

if (k <= 1) then

return (k,0)

else

(i,j) LinearFibonacci(k-1)

return (i+j,i)

kth Fibonacci NumbersLinear recursion

, 1k kF F kF

1kF

Page 60: CS201: PART 1

Analysis of Algorithms 60

kth Fibonacci Numbers

Algorithm BinaryFib(k):

Input: An integer k

Output: The kth Fibonacci number

if (k <= 1) then

return k

else

return BinaryFib(k-1)+BinaryFib(k-2)

Binary recursion

Page 61: CS201: PART 1

Analysis of Algorithms 61

properties of logarithms:

logb(xy) = logbx + logby

logb (x/y) = logbx - logby

logbxa = alogbx

logba = logxa/logxbproperties of exponentials:a(b+c) = aba c

abc = (ab)c

ab /ac = a(b-c)

b = a logab

bc = a c*logab

Summations Logarithms and Exponents

Proof techniquesBasic probability

Math you need to Review

Page 62: CS201: PART 1

Analysis of Algorithms 62

Relatives of Big-Oh

big-Omega f(n) is (g(n)) if there is a constant c > 0

and an integer constant n0 1 such that

f(n) c•g(n) for n n0

big-Theta f(n) is (g(n)) if there are constants c’ > 0 and c’’ > 0 and

an integer constant n0 1 such that c’•g(n) f(n) c’’•g(n) for n n0

little-oh f(n) is o(g(n)) if, for any constant c > 0, there is an integer

constant n0 0 such that f(n) c•g(n) for n n0

little-omega f(n) is (g(n)) if, for any constant c > 0, there is an integer

constant n0 0 such that f(n) c•g(n) for n n0

Page 63: CS201: PART 1

Analysis of Algorithms 63

Intuition for Asymptotic Notation

Big-Oh f(n) is O(g(n)) if f(n) is asymptotically less than or equal to

g(n)big-Omega

f(n) is (g(n)) if f(n) is asymptotically greater than or equal to g(n)

big-Theta f(n) is (g(n)) if f(n) is asymptotically equal to g(n)

little-oh f(n) is o(g(n)) if f(n) is asymptotically strictly less than g(n)

little-omega f(n) is (g(n)) if is asymptotically strictly greater than g(n)

Page 64: CS201: PART 1

Analysis of Algorithms 64

Example Uses of the Relatives of Big-Oh

f(n) is (g(n)) if, for any constant c > 0, there is an integer constant n0 0 such that f(n) c•g(n) for n n0

need 5n02 c•n0 given c, the n0 that satisfies this is n0 c/5 0

5n2 is (n)

f(n) is (g(n)) if there is a constant c > 0 and an integer constant n0 1 such that f(n) c•g(n) for n n0

let c = 1 and n0 = 1

5n2 is (n)

f(n) is (g(n)) if there is a constant c > 0 and an integer constant n0 1 such that f(n) c•g(n) for n n0

let c = 5 and n0 = 1

5n2 is (n2)