DS Lec2
DS Lec2
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 1
Education, Inc. All rights reserved. 0-13-140909-3
Contrast Procedural, Object Oriented Paradigms
Procedural Object-oriented
• Action-oriented — concentrates • Focuses on the nouns of problem
on the verbs specification
• Programmers: • Programmers:
– Identify basic tasks to solve – Determine objects needed for
problem problem
– Implement actions to do tasks – Determine how they should
as subprograms work together to solve the
(procedures/functions/ problem.
subroutines) – Create types called classes
– Group subprograms into made up of
programs/modules/libraries, • data members
– together make up a complete • function members to operate
system for solving the problem on the data.
– Instances of a type (class)
called objects.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 2
Education, Inc. All rights reserved. 0-13-140909-3
Structs and Classes
Similarities
• Essentially the same syntax
• Both are used to model objects with multiple
attributes (characteristics)
– represented as data members
– also called data fields or attribute variables.
• Thus, both are used to process non-
homogeneous data sets.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 3
Education, Inc. All rights reserved. 0-13-140909-3
Structs vs. Classes
Differences
• No classes in C • Both structs and
classes in C++
• Members public by • Structs can have
default members declared
private
• Class members are
private by default
• Can be specified
private • Can be specified public
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 4
Education, Inc. All rights reserved. 0-13-140909-3
Advantages in C++
(structs and classes)
• C++ structs and classes model objects
which have:
– Attributes represented as data members
– Operations represented as functions (or
methods)
• Leads to object oriented programming
– Objects are self contained
– "I can do it myself" mentality
– They do not pass a parameter to an external
function
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 5
Education, Inc. All rights reserved. 0-13-140909-3
Class Declaration
• Syntax
class ClassName
{
public:
Declarations of public members
private:
Declarations of private members
};
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 6
Education, Inc. All rights reserved. 0-13-140909-3
Designing a Class
• Data members normally placed in private:
section of a class
• Function members usually in public: section
• Typically public: section followed by private:
– although not required by compiler
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 7
Education, Inc. All rights reserved. 0-13-140909-3
Class Libraries
• Class declarations placed in header file
– Given .h extension
– Contains data items and prototypes
• Implementation file
– Same prefix name as header file
– Given .cpp extension
• Programs which use this class library called
client programs
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 8
Education, Inc. All rights reserved. 0-13-140909-3
Translating a Library
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 9
Education, Inc. All rights reserved. 0-13-140909-3
Example of User-Defined
Time Class
• Now we create a Time class
– Actions done to Time object, done by the object itself
• Note interface for Time class object,
Fig. 4.2
– Data members private – inaccessible to users of the
class
– Information hiding
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 10
Education, Inc. All rights reserved. 0-13-140909-3
Class Time: Interface
/*-- Time.h ---------------------------------------------------------------
This header file defines the data type Time for processing time.
Basic operations are: void display(ostream & out) const;
set: To set the time /*----------------------------------------------------------------------
display: To display the time Display time in standard and military format using output
-------------------------------------------------------------------------*/
stream out.
#include <iostream>
Precondition: The ostream out is open.
class Time Postcondition: The time represented by this Time object has
{ been inserted into ostream out.
public:
----------------------------------------------------------------------*/
/******** Function Members ********/
void set(unsigned hours, unsigned minutes, char am_pm);
/*---------------------------------------------------------------------- private:
Set the data members of a Time object to specified values. /********** Data Members **********/
unsigned myHours,
Preconditions: 1 <= hours <= 12, 0 <= minutes <= 59,
myMinutes;
and am_pm is either 'A' or 'P'.
Postcondition: Data members myHours, myMinutes, and char myAMorPM; // 'A' or 'P'
myAMorPM unsigned myMilTime; // military time equivalent
are set to hours, minutes, and am_pm, respectively, and
myMilTime to the equivalent military time }; // end of class declaration
----------------------------------------------------------------------*/
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 11
Education, Inc. All rights reserved. 0-13-140909-3
Constructors
• Note constructor definition in Time.cpp
example
• Syntax
ClassName::ClassName (parameter_list)
: member_initializer_list
{
// body of constructor definition
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 12
Education, Inc. All rights reserved. 0-13-140909-3
Time Constructors
//----- Definition of default constructor
Time::Time()
: myHours(12), myMinutes(0), myAMorPM('A'), myMilTime(0)
{
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 13
Education, Inc. All rights reserved. 0-13-140909-3
Constructors
• Results of explicit-value
constructor
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 14
Education, Inc. All rights reserved. 0-13-140909-3
Overloading Functions
• Note existence of multiple functions with the
same name
Time();
Time(unsigned initHours,
unsigned initMinutes,
char initAMPM);
– Known as overloading
• Compiler compares numbers and types of
arguments of overloaded functions
– Checks the "signature" of the functions
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 15
Education, Inc. All rights reserved. 0-13-140909-3
Default Arguments
• Possible to specify default values for
constructor arguments
Time(unsigned initHours = 12,
unsigned initMinutes = 0,
char initAMPM = 'A');
• Consider
Time t1, t2(5), t3(6,30), t4(8,15,'P');
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 16
Education, Inc. All rights reserved. 0-13-140909-3
Copy Operations
• During initialization
Time t = bedTime
• During Assignment
t = midnight;
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 17
Education, Inc. All rights reserved. 0-13-140909-3
Other Class Operations
• Accessors and Mutators
– See "get" and "set" functions
• Overloading operators
– Same symbol can be used more than one way
– Note declaration for I/O operators << and >>
– Note definition of overloaded I/O operators
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 18
Education, Inc. All rights reserved. 0-13-140909-3
Display and <<
//----- Definition of display function -----
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 19
Education, Inc. All rights reserved. 0-13-140909-3
Friend Functions
• Note use of two functions used for output
– display() and operator<<()
• Possible to specify operator<<() as a "friend"
function
– Thus given "permission" to access private data
elements
• Declaration in .h file (but not inside class)
friend ostream & operator<<(
ostream & out, const Time & t)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 20
Education, Inc. All rights reserved. 0-13-140909-3
Friend Functions
• Definition in .cpp file
ostream & operator<<(
ostream & out, const Time & t)
{ out << t.myHours<<":"
<<(t.myMinutes< 10? •"0":
Prefers"")
not to use friend
<<t.myMinutes function
<< ' '<<t.myAMorPM<<".M.";
• Violates principle of
return out; information hiding
}
• Note - a friend function is not member function
– not qualified with class name and ::
– receives class object on which it operates as a
parameter
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 21
Education, Inc. All rights reserved. 0-13-140909-3
Other Operations
• Advance Operation
– Time object receives a number of hours and
minutes
– Advances itself by adding to myHours,
myMinutes
• Relational Operators
– Time object compares itself with another
– Determines if it is less than the other
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 22
Education, Inc. All rights reserved. 0-13-140909-3
Redundant Declarations
• Note use of #include "Time.h" in
– Time.cpp
– Client program
• Causes "redeclaration" errors at compile time
• Solution is to use conditional compilation
– Use #ifndef and #define and #endif compiler
directives
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 23
Education, Inc. All rights reserved. 0-13-140909-3
Pointers to Class Objects
• Possible to declare pointers to class objects
Time * timePtr = &t;
• Access with
timePtr->getMilTime() or
(*timePtr).getMilTime()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 24
Education, Inc. All rights reserved. 0-13-140909-3
The this Pointer
• Every class has a keyword, this
– a pointer whose value is the address of the
object
– Value of *this would be the object itself
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 25
Education, Inc. All rights reserved. 0-13-140909-3
Recursion: The Mirrors
A function is defined recursively if it has the
following two parts
• An anchor or base case
– The function is defined for one or more specific
values of the parameter(s)
• An inductive or recursive case
– The function's value for current parameter(s) is
defined in terms of previously defined function
values and/or parameter(s)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 26
Education, Inc. All rights reserved. 0-13-140909-3
Recursive Example
• Consider a recursive power function
double power (double x, unsigned n)
{ if ( n == 0 )
return 1.0;
else
return x * power (x, n-1); }
• Which is the anchor?
• Which is the inductive or recursive part?
• How does the anchor keep it from going forever?
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 27
Education, Inc. All rights reserved. 0-13-140909-3
Recursive Example
• Note the
results of
a call
– Recursive
calls
– Resolution
of the
calls
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 28
Education, Inc. All rights reserved. 0-13-140909-3
A Bad Use of Recursion
• Fibonacci numbers
1, 1, 2, 3, 5, 8, 13, 21, 34
f1 = 1, f2 = 1 … fn = fn -2 + fn -1
– A recursive function
double Fib (unsigned n)
{ if (n <= 2) return 1;
else
return Fib (n – 1) + Fib (n – 2); }
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 29
Education, Inc. All rights reserved. 0-13-140909-3
A Bad Use of Recursion
• Why is this inefficient?
– Note the recursion tree
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 30
Education, Inc. All rights reserved. 0-13-140909-3
Uses of Recursion
• Binary Search
– See source code
– Note results of
recursive call
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 31
Education, Inc. All rights reserved. 0-13-140909-3
Binary Search
void recBinarySearch (ArrayType a, int first, int last,
ElementType item,
bool & found, int & loc)
/*-------------------------------------------------------
Recursively search sub(list) a[first] , ... a[last]
for item using a binary search.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 33
Education, Inc. All rights reserved. 0-13-140909-3
Recursion Example:
Towers of Hanoi
• Recursive algorithm especially appropriate for
solution by recursion
• Task
– Move disks from left peg to right peg
– When disk moved, must be placed on a peg
– Only one disk (top disk on a peg) moved at a time
– Larger disk may never be placed on a smaller disk
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 34
Education, Inc. All rights reserved. 0-13-140909-3
Recursion Example:
Towers of Hanoi
• Identify base case:
If there is one disk, move from A to C
• Inductive solution for n > 1 disks
– Move topmost n – 1 disks from A to B, using C
for temporary storage
– Move final disk remaining on A to C
– Move the n – 1 disk from B to C using A for
temporary storage
• View code for solution, Fig 10.4
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 35
Education, Inc. All rights reserved. 0-13-140909-3
Towers of Hanoi Sample Code
/*---------------------------------------------------------------------
Program to solve the Towers of Hanoi puzzle recursively. #include <iomanip>
return 0;
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 36
} Education, Inc. All rights reserved. 0-13-140909-3
Recursion Example:
Towers of Hanoi
• Note the graphical steps to the solution
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 37
Education, Inc. All rights reserved. 0-13-140909-3
Recursion Example: Parsing
• Examples so far are direct recursion
– Function calls itself directly
• Indirect recursion occurs when
– A function calls other functions
– Some chain of function calls eventually results in
a call to original function again
• An example of this is the problem of
processing arithmetic expressions
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 38
Education, Inc. All rights reserved. 0-13-140909-3
Recursion Example: Parsing
• Parser is part of the compiler
• Input to a compiler is
characters
– Broken up into meaningful groups
– Identifiers, reserved words, constants, operators
• These units are called tokens
– Recognized by lexical analyzer
– Syntax rules applied
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 39
Education, Inc. All rights reserved. 0-13-140909-3
Recursion Example: Parsing
• Parser generates a
parse tree using the
tokens according to
rules below:
• An expression:
term + term | term – term | term
• A term: Note the indirect
factor * factor | factor / factor | factor recursion
• A factor:
( expression ) | letter | digit
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 40
Education, Inc. All rights reserved. 0-13-140909-3
Algorithm Efficiency
• How do we measure efficiency
– Space utilization – amount of memory required
– Time required to accomplish the task
• Time efficiency depends on :
– size of input
– speed of machine
– quality of source code These vary from one
platform to another
– quality of compiler
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 41
Education, Inc. All rights reserved. 0-13-140909-3
Algorithm Efficiency
• We can count the number of times
instructions are executed
– This gives us a measure of efficiency of an
algorithm
• So we measure computing time as:
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 42
Education, Inc. All rights reserved. 0-13-140909-3
Example: Calculating the Mean
Task # times executed
1. Initialize the sum to 0 1
2. Initialize index i to 0 1
3. While i < n do following n+1
4. a) Add x[i] to sum n
5. b) Increment i by 1 n
6. Return mean = sum/n 1
Total 3n + 4
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 43
Education, Inc. All rights reserved. 0-13-140909-3
Computing Time Order of
Magnitude
• As number of inputs increases
T(n) = 3n + 4 grows at a rate proportional to n
• Thus T(n) has the "order of magnitude" n
• The computing time of an algorithm on input
of size n,
T(n) said to have order of magnitude f(n),
written T(n) is O(f(n))
if … there is some constant C such that
T(n) < Cf(n) for all sufficiently large values of n
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 44
Education, Inc. All rights reserved. 0-13-140909-3
Big Oh Notation
Another way of saying this:
• The complexity of the algorithm is O(f(n)).
• Example: For the Mean-Calculation
Algorithm:
T(n) is O(n)
• Note that constants and multiplicative
factors are ignored.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 45
Education, Inc. All rights reserved. 0-13-140909-3
Big Oh Notation
• f(n) is usually simple:
n, n2, n3, ...
2n
1, log2n
n log2n
log2log2n
• Note graph
of common
computing times
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 46
Education, Inc. All rights reserved. 0-13-140909-3
Big Oh Notation
• Graphs of common computing times
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 47
Education, Inc. All rights reserved. 0-13-140909-3
Common Computing Time
Functions
log2log2n log2n n n log2n n2 n3 2n
--- 0 1 0 1 1 2
0.00 1 2 2 4 8 4
1.00 2 4 8 16 64 16
1.58 3 8 24 64 512 256
2.00 4 16 64 256 4096 65536
2.32 5 32 160 1024 32768 4294967296
2.58 6 64 384 4096 262144 1.84467E+19
3.00 8 256 2048 65536 16777216 1.15792E+77
3.32 10 1024 10240 1048576 1.07E+09 1.8E+308
4.32 20 1048576 20971520 1.1E+12 1.15E+18 6.7E+315652
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 48
Education, Inc. All rights reserved. 0-13-140909-3
Computing in Real Time
• Suppose each instruction can be done in 1
microsecond
• For n = 256 inputs how long for various f(n)
Function Time
log2log2n 3 microseconds
Log2n 8 microseconds
n .25 milliseconds
n log2n 2 milliseconds
n2 65 milliseconds
n3 17 seconds
2n 3.7+E64 centuries!!
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 49
Education, Inc. All rights reserved. 0-13-140909-3
STL's Algorithms
• STL has a collection of more than 80 generic
algorithms.
– not member functions of STL's container classes
– do not access containers directly.
• They are stand-alone functions
– operate on data by means of iterators .
• Makes it possible to work with regular C-style
arrays as well as containers.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 50
Education, Inc. All rights reserved. 0-13-140909-3
Example of sort Algorithm
• Comes in several different forms
• One uses the < operator to compare elements
– Requires that operator<() be defined on the data
type being sorted
• The sort algorithm can be used with arrays
– Next slide
• Sort algorithm can have a third parameter
– The name of a boolean function to be used for a less
than
– See Fig. 10.9 (further explain later)
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 51
Education, Inc. All rights reserved. 0-13-140909-3
Algorithm sort
/*--------------------------------------------------------------------------
Program to illustrate use of C++'s standard sort algorithm.
#include <iostream>
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
int main()
{
int ints[] = {555, 33, 444, 22, 222, 777, 1, 66};
vector<int> v(ints, ints + 5); // Use only first 5 elements of ints
sort(v.begin(), v.end());
cout << "Sorted vector of integers:\n";
display(v);
return 0;
}
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 52
Education, Inc. All rights reserved. 0-13-140909-3
Proving Algorithms Correct
• Deductive proof of correctness may be
required
– In safety-critical systems where lives at risk
• Must specify
– The "given" or preconditions
– The "to show" or post conditions
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 53
Education, Inc. All rights reserved. 0-13-140909-3
Example: Recursive Power
Function
• Function:
double power (double x, unsigned n)
{ if ( n == 0 )
return 1.0;
else
return x * power (x, n-1); }
• Precondition:
– Input consists of a real number x and a nonnegative
integer n
• Postcondition:
– Execution of function terminates
– When it terminates value returned is xn
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 54
Education, Inc. All rights reserved. 0-13-140909-3
Example: Recursive Power
Function
• Use mathematical induction on n
– Show postcondition follows if n = 0
• Assume for n = k, execution terminates and
returns correct value
– When called with n = k + 1, inductive case
return x * power (x, n – 1) is
executed
– Value of n – 1 is k
– It follows that with n = k + 1, returns x * xk
which equals xk+1
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson 55
Education, Inc. All rights reserved. 0-13-140909-3
Proving Algorithms Correct
• Notation could be used to state assertions
S
Pre { Post = Pre (v, e ) }