You are on page 1of 52

DITP 2113 Struktur Data & Algoritma

Lecture 2: Templates, Introduction to Data Structure &


Algorithm Analysis.

Objective:
 To introduce Class Templates.
 To introduce Function Templates.
 To introduce the concepts of Data Structure & Algorithms
Analysis.
 To assure that students are able to apply the concepts in the
program.
 To assure that students are able to increase their expertise on
the topics.
Templates
 Templates are a model of a function or a class that can be
used to generate functions or classes.
 Templates provide a major implementation for code
reusability.
 From one template, different functions and classes can be
easily created.
 All functions created from a function template must have
the same interface that includes the same number of
arguments and return but their argument types and return
value are usually different.
 All classes created with a class template have the same
design but their data members and function arguments may
be different.
2
Templates
 There are two types of templates:
 Function Templates
 Class Templates

 Overloading
 The overloading concept allow the programmer to have
several functions that are doing the same task but
receive or return different types of arguments.
 For example, there are two functions that will add two
numbers together.
void Add (int x, int y);
void Add (double a, double b);
 This will cost the programmer to have a longer program.
3
Templates
 Basic Template Concepts

Generated
Function Generated
Class

Function Generated Class Generated


Template Function
Template Class

Generated
Generated
Function
Class

4
Templates
 There are 4 functions that receive different types of data but
doing the same task. What can we do about it?

int max(int x, int y) float max(float x, float y)


{ {
return (x>y)?x:y; return (x>y)?x:y;
} }

long max(long x, long y) double max(double x, double y)


{ {
return (x>y)?x:y; return (x>y)?x:y;
} }

5
Program Example
Example: Two functions are doing the same task.

//Sum.cpp
#include <iostream>
using namespace std;

//Add 2 integer
void Add(int, int);

//Add 2 double
void Add(double, double);

int main()
{
Add(10, 12); //method call for int
Add(5.5, 3.8); //method call for double
return 0;
}

6
Program Example
Example: Two functions are doing the same task (cont).

//Function implementation
void Add(int x, int y)
{
cout << "Integer: " << x << " + " << y << " = " << x + y << endl;

void Add(double x, double y)


{
cout << "Double: " << x << " + " << y << " = " << x + y << endl;

7
Program Example
Example: Two functions are doing the same task (cont).

Output : Integer : 10 + 12 = 22
Double : 5.5 + 3.8 = 9.3

 When the first method is called, the compiler will define


that there are two integer numbers being send to the
equivalent method that receive two integers. Same goes
with the second method that receive two doubles.
 During executions, both functions will add two numbers
together but the difference is the types of data.
 What will happen if we have 5 types of data? Do we have
to create 5 functions then?
 Templates can solve this problem.
8
Function Templates
 A function applies actions to one or more objects and may
create and return one object.
 Function Templates can create multiple functions each with
potentially different arguments and return types.
 The template prototype is known as template prefix.
 Syntax Declaration:
template <class identifier>
 Example:
template <class T>
template <class data>
template <class dataType>

*Note : T, data and dataType must be a valid identifier.

9
Function Templates
 The declaration for standard data types:
int x; double y;

 The declaration for class generic data types:


template <class T>
T x;
OR
template <class dataType>
dataType x;

*Note : T and dataType will be the class generic type that can represent
any type of standard data type

10
Program Example
Example: Function Templates.

//Sum.cpp
#include <iostream>
using namespace std;

template <class T> //template prefix

void Add (T x, T y)
{ cout << x << " + " << y << " = "
<< x + y << endl;
}

int main()
{
Add (10, 12);
Add (5.5, 3.8);
return 0;
}
11
Function Templates
 Only one function template needed to allow any method call
with different data types being send to its parameters.

 The class generic data type will change according to the


type of data being send to them.

 The function will add two numbers and prints out the result
according to the data type.

12
Function Templates
 Function Template With More Than One Parameter
 A function template can have more than one parameter.
 Syntax Declaration:
template <class T1, class T2>

 T1 and T2 can be two different data types. For example,


T1 can be used to represent an integer while T2 can be
used to represent a char.

 Both templates are separated by comma during its


definition.

13
Program Example
Example: Function Template with more than one parameter.

//Printing.cpp
#include <iostream>
using namespace std;
template < class T1, class T2 >

void printData (T1 var1, T2 var2)


{
cout << “First value is " << var1;
cout << “\nSecond value is " << var2;
}
int main ()
{
int v1;
char v2;
cout << " Enter an integer and a char : ";
cin >> v1 >> v2;
printData (v1, v2);
return 0;
}
14
Program Example
Example: Function Template with more than one parameter (cont).

Output : Enter an integer and a char: 5 A


The first value is: 5
The second value is: A

 Both generic data types can be used to represent two


different data types at the same time.

 The first class generic data type T1 will be used to


represent an integer while the second class generic data
type T2 will be used to represent a char.

15
Function Templates
 Function Template With Multiple Type Of Parameters
 Besides the generic data type, the parameter in the
function can also be other standard data types such as
integer, float, double, boolean and char.

 At least one of the parameter must be the class generic


data type.

 Syntax Declaration:
template <class T>
void Maximum (T x, int y);

16
Program Example
Example: Function Template with multiple type of parameter.

//PrintArray.cpp
#include <iostream>
using namespace std;

template <class T>


void printArray (T *array, int count) {
for (int i=0; i<=count-1; ++i)
cout << array [i] << " ";
}
int main() {
char arrayA [] = “Success";
float arrayB [] = {10.5, 40.7, 21.3, 41.5};
cout << " The values in arrayA : ";
printArray(arrayA, 8);
cout << " \nThe values in arrayBB : ";
printArray(arrayB, 4);
return 0;
}
17
Program Example
Example: Function Template with multiple type of parameter (cont).

Output : The values in arrayA: Success


The values in arrayB: 10.5 40.7 21.3 41.5

18
Class Templates
 Sometimes there is a situation that needed a generic class
being declared.

 Class Template is defined to have the data member with


the generic type.

 The declaration of class template is just the same as the


function template:
template <class T>

 The difference is that the generic parameters must be used


to at least one of the class data member.

19
Program Example
Example: Class Template.

//Maximum.h
#ifndef MAXIMUM_H
#define MAXIMUM_H

template <class T>

class Maximum {
private:
T val1, val2;
public:
Maximum(T v1, T v2);
void findMax();
};
#endif

20
Program Example
Example: Class Template (cont).

template <class T>


Maximum<T>::Maximum(T v1, T v2) {
val1 = v1;
val2 = v2; }

template <class T>


void Maximum<T>::findMax() {
T max;
if (val1 > val2)
max = val1;
else
max = val2;
cout << “The maximum value is " << max;
}

21
Program Example
Example: Class Template (cont).

//MaxMain.cpp
#include <iostream>
#include "Maximum.h"
using namespace std;

int main()
{
Maximum <int> object1(100, 13);
Maximum <char> object2('a', 'A');
object1.findMax();
cout << "\n";
object2.findMax();
return 0;
}

22
Program Example
Example: Class Template (cont).

Output : The maximum value is : 100


The maximum value is : a

 The template prefix must be define before the declaration


of each class and each functions implementation.
 The class interface and implementation must be included
into one header file.
 Template will be compiled only when it is requested
(compile on demand) and it won’t be compiled until the
object instantiation is requested.

23
Intro to Data Structures & Algorithm

 Although several tools are used to define algorithms, one of


the most common is pseudocode.
 Pseudocode is an English-like representation of the code
required for an algorithm.
 It is part English, part structured code.
 The English part provides a relaxed syntax that is easy to
read.
 The code part consists of an extended version of the basic
algorithmic constructs such as sequence, selection and
iteration.

24
Algorithm Header
 Each algorithm begins with a header that names it, describe
its parameters and lists any pre- and postconditions.

 This information is important because the programmer


using the algorithm often sees only the header information
not the complete algorithm.

 Therefore the header information must be complete enough


to communicate to the programmer everything that must
know to use the algorithm.

25
Algorithm Header
 Example of Algorithm Header:

Algorithm search (val list <array>,


val argument <integer>,
ref location <index>)

Search array for specific item and return index location

Pre list contains data array to be searched


argument contains data to be located in list
Post location contains index of element matching argument -or-
undetermined if not found
Return <Boolean> true if found, false if not found.

26
Algorithm Header
 Example of Pseudocode:

Algorithm average
Pre nothing
Post average and numbers printed

1 i=0;
2 loop(not end of file)
1 read number into array[i]
2 sum = sum + number
3 i = i + 1;
3 end loop
4 average = sum /i
5 print (average)
end average

27
Abstract Data Type (ADT)
 A data type consists of two parts, a set of data and the operations that
can be performed on the data.
 Integer type consists of values (whole numbers in some defined range)
and operations (add, subtract, multiply, divide and any other operations
appropriate for the application).
 Atomic Data
 Atomic data are data that we choose to consider as a single, non
decomposable entity.
 For example, the integer 4562 may be considered as a single
integer value. Although it can be decomposed into digits but it will
not have the same characteristics of the original value.
 Atomic data type is a set of atomic data with identical properties that
are defined by the set of values and a set of operations that act on
the values.

28
Abstract Data Type (ADT)
 Composite Data.
 Composite data can be broken out into subfields that have
meaning.
 For example, a telephone number can be decomposed into
three parts, the state code (06), the district code(233) and the
phone number(2512).

29
Data Structure
 A data structure is an aggregation of atomic and composite
data types into a set with defined relationships.
 Structure means a set of rules that hold the data together.
 Data structures can be nested. It can consists of other data
structures.

Array Record
Homogeneous sequence of Heterogeneous combination of
data or data types known as data into a single structure with
elements an identified key
Position association among the No association
elements

30
Abstract Data Type (ADT)
 An abstract data type is a data declaration packaged
together with the operations that are meaningful for the data
type.
 The ADT consists of a set of definitions that allow
programmers to use the functions while hiding the
implementation. This is known as abstraction.
 With ADT, users are not concerned with how the task is
done but rather with what it can do. For example, the
concepts of a list. At least three data structures will support
list such as an array, a linked list or a file.
 Users should not be aware of the structure used. As long as
they know that they can insert and retrieve data, it should
make no difference on how the data is stored..
31
Abstract Data Type (ADT)
 Each ADT class object will have a defined type that the
users must use in their programs.

 When the ADT class object is created, it contains any


required structures.

 The exact format and type of the structures are not a


concern of the application code.

32
Abstract Data Type (ADT)
 A Model for an Abstract Data Type

ADT Class
Application Program
Object

ADT class code


Search Create Delete

Dynamic Memory
ADT Data
Structure

33
Algorithm Analysis
 Algorithm – A set of instructions that must be followed by
the computer to solve problems.
 Algorithm Analysis – A technique to analyze an algorithm,
its efficiency and the usage of memory to find the best
algorithm.
 An algorithm should have such characteristic:
 Solve the problem successfully
 An efficient use of memory
 Fast run time
 The run time usually depends on:
 Input size of the program
 Code quality
 Computer speed
 Algorithm complexity 34
Algorithm Analysis
 There are two types of algorithm:
 Algorithm 1 – The algorithm is easier to understand,
encode and debug.
 Algorithm 2 – The algorithm that use the computer
resource like CPU memory and speed with efficient.
 Algorithm 1 can be used if the function / method is only used
a few times in the program.
 This is to minimize the cost and input size.
 Algorithm 2 can be used if the function / method is used a
lot of times and using a bigger input size.
 This is because it is important to minimize the cost in
developing the program.

35
Algorithm Analysis
 Example of the program:
Example 1:
total = 0;
for (int i=0; i <= n; i++)
total = total + i;

Example 2:
total = n * (n + 1)/2;

 Both algorithms are doing the same task but the Example 1
can be understand easily while the Example 2 is much
simpler.

36
Algorithm Analysis
n total (Eg 1) total (eg 2)
Example 1  5 5 1
needs to execute 10 10 1
instruction total 15 15 1
for n times. 20 20 1

Number of
Example 2  Executions
needs to execute
instruction total
only once.
1

n
37
Algorithm Analysis
 There are 3 scenario to estimate the efficiency is using
computer resource during run time:
 Worst Case Scenario
 Best Case Scenario
 Average Case Scenario / Theta Notation

 The important of analyzing the efficiency depends on the


type of software application being developed.

 For example, the critical application such as the air traffic


control, medical system and application for army need to
have the worst case scenario analyzed.

38
Algorithm Efficiency
 Brassard and Bratley used the term algorithmics which
defines as “The systematic study of the fundamental
techniques used to design and analyze efficient algorithms.”
 If a function is linear (contains no loops) then its efficiency is a
function of the number of instructions it contains.
f(n) = efficiency
 Linear Loops
1 i=1
2 loop (i<=1000)
1 application code
2 i = i + 1
3 end loop
 Assuming i is an integer, the loop is repeated for 1000 times.
f(n) = n
39
Algorithm Efficiency
 Linear loops with the number of iterations is half the loop
factor. The higher the factor the lower the number of loops.
1 i=1
2 loop (i<=1000)
1 application code
2 i = i + 2
3 end loop
 Assuming i is an integer, the loop is repeated for 500 times.
f(n) = n / 2

40
Algorithm Efficiency
 Logarithmic Loops:
 Multiply Loops
1 i=1
2 loop (i<1000)
1 application code
2 i = i * 2
3 end loop
 Divide Loops
1 i=1
2 loop (i<1000)
1 application code
2 i = i / 2
3 end loop
 How many times has the loops repeated?
41
Algorithm Efficiency
Multiply Divide
Loop Value of i Loop Value of i
1 1 1 1000
2 2 2 500
3 4 3 250
4 8 4 125
5 16 5 62
6 32 6 31
7 64 7 15
8 128 8 7
9 256 9 3
10 512 10 1
(exit) 1024 (exit) 0
42
Algorithm Efficiency
 The number of iterations is 10 in both cases.
 The reason is that in each iteration the value of i doubles for
the multiply loop and is cut in half for the divide loop.
 The number of iterations is a function of the multiplier or
divisor, in this case is 2.
 The loop continues while the condition shown below is true.
Multiply: 2ⁿ< 1000
Divide: 1000 / 2ⁿ>= 1
n = iterations
 Iterations in loops that multiply or divide are determined by
the following formula.
f(n) = [log₂ n]

43
Summary
LINEAR LOOPS
For + and – operations the f(n) is equivalent to n.
If i (+ or – ) any constant number the efficiency is n/
(constant number)
LOGARITHMIC LOOPS
For * and / operations the f(n) is log [constant number] n

44
Algorithm Efficiency
 Nested Loops must be determined on how many iterations
each loops completes.
 The total is then the product of the number of iterations in
the inner loop and the number of iterations in the outer loop.
 The loop continues while the condition shown below is true.
Iterations = outer loop iterations x
inner loop iterations

 There are three types of nested loops; linear logarithmic,


dependent quadratic and quadratic

45
Algorithm Efficiency
 Linear Logarithmic
1 i=1
2 loop (i<=10)
1 j=1
2 loop(j<=10)
1 application code
2 j = j * 2
3 end loop
4 i = i + 1
3 end loop

 The number of iterations in the inner loop is therefore


[log₂ 10]

46
Algorithm Efficiency
 However, because the inner loop is controlled by an outer
loop, the above formula must be multiplied by the number of
times the outer loop executes which is 10.
10 x [log₂ 10]

 Which is generalized as
f(n) = [nlog₂ n]

47
Algorithm Efficiency
 Dependent Quadratic
1 i=1
2 loop (i<=10)
1 j=1
2 loop(j<=i)
1 application code
2 j = j + 1
3 end loop
4 i = i + 1
3 end loop

48
Algorithm Efficiency
 The outer loop is the same as the previous loop. However
the inner loop depends on the outer loop for one of its
factors. The number of iterations in the body of the inner
loop is calculate asshown below
1 + 2 + 3 + . . . + 9 + 10 = 55

 Multiplying the inner loop by the number of times the outer


loop is executed gives the following formula for a
dependent quadratic
f(n) = n n + 1
2

49
Algorithm Efficiency
 Quadratic
1 i=1
2 loop (i<=10)
1 j=1
2 loop(j<=10)
1 application code
2 j = j + 1
3 end loop
4 i = i + 1
3 end loop

50
Algorithm Efficiency
 Each loop executes the same number of times.
 The outer loop is executed ten times. For each of its
iterations, the inner loop is also executed ten times.
10 x 10 = 100

 This formula generalizes to


f(n) = n²

51
The End

Q&A

52

You might also like