advertisement

University of Bahrain Information Technology College Department of Computer Science ITCS 345 / Tutorial # 1 (Date: Tuesday, February 09, 2016) Algorithm analysis allows us to compare algorithms. The factors involved in this comparison are efficiency and running time which are linked to each other. The running time of an algorithm will typically change depending on the size of input. Algorithms have a best case, average case, and worse case running time. Pseudocode Running time can be estimated in a more general manner by using Pseudocode to represent the algorithm as a set of fundamental operations which can then be counted. Pseudocode contains all of the following features: Conventional loops: o o o o o Method declaration: o o o If... then... else... While... do... Repeat... until... For... do... Indentation is used instead of parentheses (brackets) Method name: Algorithm methodName(args) Input description: Input... Output description: Output... Method calls: var.methodName(args) Return values: return... Expressions: o o Assignment: Equality comparison: = In a pseudocode description of an algorithm, each line can be viewed as a certain number of operations which can be counted and added up to find a total value for the algorithm. Some examples are shown below: varNumber X[1] (2 operations - 1 array value retrieval, 1 assignment) For a 1 to n do... (n operations - any operations within this loop will then be multiplied by n also as they will be carried out n times) return varNumber Trace the following algorithm when: Ms Sawsan Hussain Office: S40-1060 Page 1 1. Find the output of the following algorithm , assume n=5 Algorithm S S 0 For i 1 to n do S S+i*i-1 2. Find the output of the following algorithm , assume A = { 2,5,2,7,6} Algorithm S (A[1..n]) S 0 For i 1 to n do S S+A[i] Return S 3. Find the output of the following algorithm , assume A = { 9,2,10,5,11,6,4} Algorithm S (A[1..n]) Max A[i] Min A[i] For i 2 to n do If A[i] < Min then Min A[i] Else If A[i] > Max then Max A[i] Return Min,Max Recursive Algorithm Is an algorithm which calls itself with "smaller (or simpler)" input values, and which obtains the result for the current input by applying simple operations to the returned value for the smaller (or simpler) input. More generally if a problem can be solved utilizing solutions to smaller versions of the same problem, and the smaller versions reduce to easily solvable cases, then one can use a recursive algorithm to solve that problem. Trace the following algorithm when: 4. Find the output of the following algorithm , assume n = 3 Algorithm S (n) If n = 0 Else Ms Sawsan Hussain then return 1 return n * S(n-1) Office: S40-1060 Page 2