Revision of C++
// function returning the max between two numbers int max(int num1, int num2) { // local variable declaration int result; if (num1 > num2) result = num1; else result = num2; return result; }
Primitive operations Assigning a value to a variable Calling a function Performing an arithmetic operation Comparing two values Indexing to an array Returning from a function
Describe: in natural language / pseudo- code / diagrams / etc. Algorithm: Finite set of instructions that, if followed, accomplishes a particular task. Describe: in natural language / pseudo- code / diagrams / etc. Often more important than space complexity space available (for computer programs!) tends to be larger and larger time is still a problem for all of us Algorithm Analysis I Weiss, chap.2
Algorithm Analysis Space complexity Time complexity How much space is required Time complexity How much time does it take to run the algorithm Often, we deal with estimates!
Pseudocode High-level description of an algorithm. Algorithm arrayMax(A, n) Input array A of n integers Output maximum element of A currentMax A[0] for i 1 to n 1 do if A[i] currentMax then currentMax A[i] return currentMax Example: find the max element of an array High-level description of an algorithm. More structured than plain English. Less detailed than a program. Preferred notation for describing algorithms. Hides program design issues. Algorithm Analysis I Weiss, chap.2
Best, worst, average-case time We usually consider the worst-case while analyzing an algorithm See pages 10 + 11 in Malik See examples with false condition loop
Running time Suppose the program includes an if-then statement that may execute or not: variable running time Typically algorithms are measured by their worst case
Big-O notation f(n) = O(n) Reads: f(n) is Big-Oh of n Why? It is becoming increasingly exact as a variable approaches a limit, usually infinity. See Malik page 14
Algorithm Analysis (Time complexity) The driver examples first 2N N*N 2n and n*n, with real values of n … (Malik page 10) By analyzing a particular algorithm, we usually count the number of Primitive Operations
Equation for running time = c1. n + d1 Time complexity is O(n) What is the time complexity of search? Binary Search algorithm at work O(log n) Sequential search? O(n) Equation for running time = c1. n + d1 Time complexity is O(n)
Examples O(1) 1. Accessing Array Index (int a = ARR[5];) 2. Inserting a node in Linked List 3. Pushing and Poping on Stack O(n) time 1. Traversing an array 2. Traversing a linked list 3. Linear Search
O(log n) time Binary Search Finding largest/smallest number in a binary search tree O(nlogn) time Merge Sort
Classes and Constructors
The end