+ All Categories
Home > Documents > Chapter 2 Data Design and Implementation

Chapter 2 Data Design and Implementation

Date post: 03-Jan-2016
Category:
Upload: edan-velazquez
View: 40 times
Download: 0 times
Share this document with a friend
Description:
Chapter 2 Data Design and Implementation. Lecture 4. The representation of information in a manner suitable for communication or analysis by humans or machines Data are the nouns of the programming world: The objects that are manipulated The information that is processed. Data. - PowerPoint PPT Presentation
93
Chapter 2 Data Design and Implementation 1
Transcript
Page 1: Chapter 2 Data Design and Implementation

Chapter 2Data Design and Implementation

1

Page 2: Chapter 2 Data Design and Implementation

Lecture 4

Page 3: Chapter 2 Data Design and Implementation

Data

• The representation of information in a manner suitable for communication or analysis by humans or machines

• Data are the nouns of the programming world: • The objects that are manipulated• The information that is processed

3

Page 4: Chapter 2 Data Design and Implementation

Data Abstraction

• Separation of a data type’s logical properties from its implementation

LOGICAL PROPERTIES IMPLEMENTATION

What are the possible values? How can this be done in C++?

What operations will be needed? How can data types be used?

4

Page 5: Chapter 2 Data Design and Implementation

APPLICATION

0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1

REPRESENTATION

Data Encapsulation

• is the separation of the representation of data from the applications that use the data at a logical level; • a programming language feature that enforces

information hiding

int y;

y = 25;

5

Page 6: Chapter 2 Data Design and Implementation

Encapsulated C++ Data Type int

Value range: INT_MIN . . INT_MAX

Operations: + prefix - prefix + infix - infix * infix / infix % infixRelational Operators infix

TYPE int

(inside)

Representation of

int

as 16 bits two’s complement

+

Implementation of Operations

6

Page 7: Chapter 2 Data Design and Implementation

Abstract Data Type (ADT)

• A data type whose properties (domain and operations) are specified independently of any particular implementation.

7

Page 8: Chapter 2 Data Design and Implementation

Collection ordered in different ways

8

Page 9: Chapter 2 Data Design and Implementation

Data from 3 different levels

9

• Application (or user) level: modeling real-life data in a specific context.

• Logical (or ADT) level: abstract view of the domain and operations. WHAT

• Implementation level: specific representation of the structure to hold the data items, and the coding for operations. HOW

Page 10: Chapter 2 Data Design and Implementation

Communication between the Application Level and Implementation Level

10

Page 11: Chapter 2 Data Design and Implementation

Viewing a library from 3 different levels

• Application (or user) level: Library of Congress, or Baltimore County Public Library.

• Logical (or ADT) level: domain is a collection of books; • operations include: check book out, check book in,

pay fine, reserve a book.

• Implementation level: representation of the structure to hold the “books”, and the coding for operations.

11

Page 12: Chapter 2 Data Design and Implementation

Composite Data Type

A composite data type is a type which

• stores a collection of individual data components under one variable name,

• and allows the individual data components to be accessed.

12

Page 13: Chapter 2 Data Design and Implementation

4 Basic Kinds of ADT Operations

• Constructor -- creates a new instance (object) of an ADT.

• Transformer -- changes the state of one or more of the data values of an instance.

• Observer -- allows us to observe the state of one or more of the data values without changing them.

• Iterator -- allows us to process all the components in a data structure sequentially.

13

Page 14: Chapter 2 Data Design and Implementation

Two Forms of Composite Data Types

Components are not organized with respect to one another.

The organization determines method used to access individual data components.

UNSTRUCTURED STRUCTURED

EXAMPLES: EXAMPLES: arraysclasses and structs

14

Page 15: Chapter 2 Data Design and Implementation

C++ Built-In Data Types

Composite

array struct union class

Address

pointer reference

Simple

Integral Floating

char short int long enum

float double long double

15

Page 16: Chapter 2 Data Design and Implementation

Records

A record is a composite data type made up of a finite collection of not necessarily homogeneous elements called members or fields.

For example . . .

.year 2008

.maker ‘h’‘o’‘n’‘d’ ‘a’‘\0’ . . .

.price 18678.92

thisCar at Base Address 6000

16

Page 17: Chapter 2 Data Design and Implementation

struct CarType

struct CarType{

int year; char maker[10]; float price;

} ;

CarType thisCar; //CarType variables

CarType myCar;

17

Page 18: Chapter 2 Data Design and Implementation

Accessing struct members

The member selection operator (period . ) is used between the variable name and the member identifier to access individual members of a record (struct or class) type variable.

EXAMPLES

myCar.year

thisCar.maker[4]

18

Page 19: Chapter 2 Data Design and Implementation

Valid struct operations

• Operations valid on an entire struct type variable:

assignment to another struct variable of same type,

pass as a parameter to a function

(either by value or by reference),

return as the value of a function.

19

Page 20: Chapter 2 Data Design and Implementation

Pass-by-value

CALLINGBLOCK

FUNCTION CALLED

sends a copy of the contents of the actual parameter

SO, the actual parameter cannot be changed by the function.

20

Page 21: Chapter 2 Data Design and Implementation

Pass-by-reference

sends the location (memory address)of the actual parameter

can change value ofactual parameter

CALLINGBLOCK FUNCTION

CALLED

21

Page 22: Chapter 2 Data Design and Implementation

Using struct type Reference Parameter to change a member

void AdjustForInflation(CarType& car, float perCent)

// Increases price by the amount specified in perCent{

car.price = car.price * perCent + car.price; };

SAMPLE CALL

AdjustForInflation(myCar, 0.03);

22

Page 23: Chapter 2 Data Design and Implementation

Using struct type Value Parameter to examine a member

bool LateModel(CarType car, int date)

// Returns true if the car’s model year is later than// or equal to date; returns false otherwise.{

return ( car.year >= date ) ;

};

SAMPLE CALL

if ( LateModel(myCar, 1995) )std::cout << myCar.price << std::endl;

23

Page 24: Chapter 2 Data Design and Implementation

One-Dimensional Array at the Logical Level

A one-dimensional array is a structured composite data type made up of

a finite,

fixed size (known at compile time)

collection of homogeneous (all of the same data type) elements

having relative positions and

to which there is direct access (any element can be accessed immediately).

Array operations (creation, storing a value, retrieving a value) are performed using a declaration and indexes.

24

Page 25: Chapter 2 Data Design and Implementation

Implementation Example

float values[5]; // assume element size is 4 bytes

This ACCESSING FUNCTION gives position of values[Index]

Address(Index) = BaseAddress + Index * SizeOfElement

Base Address

values[0] values[1] values[2] values[3] values[4]

7000 7004 7008 7012 7016

Indexes 25

Page 26: Chapter 2 Data Design and Implementation

One-Dimensional Arrays in C++

• The index must be of an integral type • char, short, int, long, or enum

• The index range is always 0 through the array size minus 1

• Arrays cannot be assigned one to another, • and cannot be the return type of a function

26

Page 27: Chapter 2 Data Design and Implementation

Another Example

char name[10]; // assume element size is 1 byte

name[0] name[1] name[2] name[3] name[4] . . . . . name[9]

6000 6001 6002 6003 6004 6005 6006 6007 6008 6009

Base Address

This ACCESSING FUNCTION gives position of name[Index]

Address(Index) = BaseAddress + Index * SizeOfElement

27

Page 28: Chapter 2 Data Design and Implementation

Passing Arrays as Parameters

• In C++, arrays are always passed by reference, • and & is not used with the formal

parameter type.

• Whenever an array is passed as a parameter, its base address is sent to the called function.

28

Page 29: Chapter 2 Data Design and Implementation

const array parameter

Because arrays are always passed as reference parameters, you can protect the actual parameter from unintentional changes by using const in formal parameter list and function prototype.

FOR EXAMPLE . . . // prototype

float SumValues( const float values[ ],

int numOfValues );

29

Page 30: Chapter 2 Data Design and Implementation

float SumValues (const float values[ ], numOfValues)

// Pre: values[ 0] through values[numOfValues-1]

// have been assigned

// Returns the sum of values[0] through

// values[numOfValues-1]

{

float sum = 0;

for ( int index = 0; index < numOfValues;

index++ )

{

sum = values [index] + sum;

}

return sum;

}

30

Page 31: Chapter 2 Data Design and Implementation

Two-Dimensional Array at the Logical Level

A two-dimensional array is a structured composite data type made up of a finite, fixed size collection of homogeneous elements having relative positions and to which there is direct access.

Array operations (creation, storing a value, retrieving a value) are performed using a declaration and a pair of indexes (called row and column) representing the component’s position in each dimension.

31

Page 32: Chapter 2 Data Design and Implementation

EXAMPLE -- To keep monthly high temperatures for 50 states in a two-dimensional array.

const int NUM_STATES = 50 ;const int NUM_MONTHS = 12 ;int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ;

[ 0 ] [ 1 ] [ 2 ] . . stateHighs [2]

[7] . [ 48 ] [ 49 ]

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

66 64 72 78 85 90 99 115 98 90 88 80row 2,col 7might beArizona’shigh forAugust

32

Page 33: Chapter 2 Data Design and Implementation

Finding the average high temperature for Arizona

float total = 0;

int month;

float average;

for ( month = 0; month < NUM_MONTHS;

month ++ )

total = total + stateHighs [ 2 ][ month ];

average = ( total / NUM_MONTHS);

33

Page 34: Chapter 2 Data Design and Implementation

const int NUM_STATES = 50 ;const int NUM_MONTHS = 12 ;int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ;

• In memory, C++ stores arrays in row order. The first row is followed by the second row, etc.

12 highs for state 0 12 highs for state 1 etc. Alabama Alaska first row second row

8000 8024 8048

Base Address

STORAGE

. . .

rows columns

34

Page 35: Chapter 2 Data Design and Implementation

Implementation Level View

stateHighs[ 0 ] [ 0 ]stateHighs[ 0 ] [ 1 ]stateHighs[ 0 ] [ 2 ]stateHighs[ 0 ] [ 3 ]stateHighs[ 0 ] [ 4 ]stateHighs[ 0 ] [ 5 ]stateHighs[ 0 ] [ 6 ]stateHighs[ 0 ] [ 7 ]stateHighs[ 0 ] [ 8 ]stateHighs[ 0 ] [ 9 ]stateHighs[ 0 ] [10 ]stateHighs[ 0 ] [11 ]stateHighs[ 1 ] [ 0 ]stateHighs[ 1 ] [ 1 ]stateHighs[ 1 ] [ 2 ]stateHighs[ 1 ] [ 3 ] . . .

To locate an element such asstateHighs [ 2 ] [ 7] the compiler needs to know that there are 12 columnsin this two-dimensional array.

At what address will stateHighs [ 2 ] [ 7 ] be found?

Assume 2 bytes for type int.

Base Address 8000

35

Page 36: Chapter 2 Data Design and Implementation

Example of a 2-dimensional object

36

Page 37: Chapter 2 Data Design and Implementation

Two-Dimensional Array Parameters

• Just as with a one-dimensional array, when a two- (or higher) dimensional array is passed as a parameter, the base address of the actual array is sent to the function.

• The size of all dimensions except the first must be included in the function heading and prototype.

• The sizes of those dimensions for the formal parameter must be exactly the same as in the actual array.

37

Page 38: Chapter 2 Data Design and Implementation

const int NUM_STATES = 50 ;const int NUM_MONTHS = 12 ;int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ;float stateAverages [ NUM_STATES ] ;

[ 0 ] ? [ 1 ] ? [ 2 ] . . . [ 48 ] [ 49 ]

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

43 42 50 55 60 78 79 80 77 72 63 4066 64 72 78 85 90 99 115 98 90 88 80

Use the two-dimensional stateHighs array to fill a

one-dimensional stateAverages array

Alaska

Arizona

38

Page 39: Chapter 2 Data Design and Implementation

void findAverages (const int stateHighs [NUM_STATES] [NUM_MONTHS],

int stateAverages [NUM_STATES])

// Pre: stateHighs[ 0..NUM_STATES-1] [ 0..NUM_MONTHS-1] // assigned// Post: stateAverages[ 0..NUM_STATES-1 ] contains rounded // high temperature for each state{ int state; int month; float total; for ( state = 0 ; state < NUM_STATES; state++ ) { total = 0.0; for ( month = 0 ; month < NUM_MONTHS ; month++ )

total = stateHighs [ state ][ month ] + total; stateAverages [ state ] = total / NUM_MONTHS;

}}

39

Page 40: Chapter 2 Data Design and Implementation

Lecture 5

Page 41: Chapter 2 Data Design and Implementation

Using typedef with arrays

helps eliminate the chances of size mismatches between

formal and actual parameters.

FOR EXAMPLE,

typedef int StateHighsType [ NUM_STATES ][ NUM_MONTHS ];

typedef float StateAveragesType [ NUM_STATES ];

void findAverages( const StateHighsType stateHighs, StateAveragesType stateAverages )

{

.

.

.

}

41

Page 42: Chapter 2 Data Design and Implementation

Declaring Multidimensional Arrays

EXAMPLE USING TYPEDEF

const int NUM_DEPTS = 5;

// mens, womens, childrens, electronics, linens

const int NUM_MONTHS = 12 ;

const int NUM_STORES = 3 ;

// White Marsh, Owings Mills, Towson

typedef long MonthlySalesType [NUM_DEPTS] [NUM_MONTHS]

[NUM_STORES];

MonthlySalesType monthlySales;

42

Page 43: Chapter 2 Data Design and Implementation

43

const int NUM_DEPTS = 5; // mens, womens, childrens, electronics,linensconst int NUM_MONTHS = 12 ; const int NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson

typedef long MonthlySalesType [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES] ;MonthlySalesType monthlySales;

monthlySales[3][7][0]sales for electronics in August at White Marsh

12 MONTHS columns

5 D

EP

TS

ro

ws

3 STORES

sheets

43

Page 44: Chapter 2 Data Design and Implementation

C++ class data type

• A class is an unstructured type that encapsulates a fixed number of

data components (data members) with the functions (called member functions) that

manipulate them.

• The predefined operations on an instance of a class are whole assignment and component access.

44

Page 45: Chapter 2 Data Design and Implementation

class DateType Specification

// SPECIFICATION FILE ( datetype.h )

class DateType // declares a class data type{

public : // 4 public member functions

void Initialize (int newMonth, int newDay, int newYear ) ;int GetYear( ) const ; // returns yearint GetMonth( ) const ; // returns monthint GetDay( ) const ; // returns day

private : // 3 private data members

int year ; int month ; int day ;

}; ; must be there!!!

Page 46: Chapter 2 Data Design and Implementation

Use of C++ data type class

• Variables of a class type are called objects (or instances) of that particular class.

• Software that declares and uses objects of the class is called a client.

• Client code uses public member functions (called methods in OOP) to handle its class objects.

• . means calling a public member function.

46

Page 47: Chapter 2 Data Design and Implementation

Client Code Using DateType#include “datetype” // includes specification of the classusing namespace std;int main ( void ){ DateType startDate; // declares 2 objects of DateType DateType endDate; bool retired = false; startDate.Initialize ( 6, 30, 1998 ); endDate.Initialize ( 10, 31, 2002 ); cout << startDate.MonthIs( ) << “/” << startDate.DayIs( ) << “/” << startDate.YearIs( ) << endl; while ( ! retired ) { // finishSomeTask } }

47

Page 48: Chapter 2 Data Design and Implementation

// SPECIFICATION FILE ( datetype .h ) // Specifies the data and function members. class DateType { public: . . .

private: . . . } ;

// IMPLEMENTATION FILE ( datetype.cpp )

// Implements the DateType member functions. . . .

2 separate files generally used for class type

48

Page 49: Chapter 2 Data Design and Implementation

DateType Class Instance Diagrams

Initialize

GetYear

GetMonth

GetDay

startDate endDate

Private data:

year

month

day

2002

10

31

Initialize

GeytYear

GetMonth

GetDay

1998

6

30

Private data:

year

month

day

49

Page 50: Chapter 2 Data Design and Implementation

Implementation of DateType member functions

// IMPLEMENTATION FILE (datetype.cpp)

#include “datetype.h” // also must appear in client code

void DateType :: Initialize ( int newMonth,

int newDay,

int newYear )

// Post: year is set to newYear.

// month is set to newMonth.

// day is set to newDay.

{

year = newYear;

month = newMonth;

day = newDay;

}

50

Page 51: Chapter 2 Data Design and Implementation

51

int DateType :: GetMonth ( ) const// Accessor function for data member month{ return month;}

int DateType :: GetYear ( ) const// Accessor function for data member year{ return year;}

int DateType :: GetDay ( ) const// Accessor function for data member day{ return day;}

51

Page 52: Chapter 2 Data Design and Implementation

Familiar Class Instances and Member Functions

• The member selection operator ( . ) selects either data members or member functions.

• Header files iostream and fstream declare the istream, ostream, and ifstream, ofstream I/O classes.

• Both cin and cout are class objects and get and ignore are member functions.

cin.get (someChar);cin.ignore (100, ‘\n’);

• These statements declare myInfile as an instance of class ifstream and invoke member function open.

ifstream myInfile ;myInfile.open ( “mydata.dat” );

52

Page 53: Chapter 2 Data Design and Implementation

Scope Resolution Operator ( :: )

• C++ programs typically use several class types.

• Different classes can have member functions with the same identifer, like Write( ).

• Member selection operator is used to determine the class whose member function Write( ) is invoked.

currentDate.Write( ) ; // class DateTypenumberZ.Write( ) ; // class ComplexNumberType

• In the implementation file, the scope resolution operator is used in the heading before the member function’s name to specify its class.

void DateType :: Write ( ) const{ . . .

} 53

Page 54: Chapter 2 Data Design and Implementation

Inheritance

54

Page 55: Chapter 2 Data Design and Implementation

A Short Review of Object-Oriented Programming

• Three inter-related constructs: classes, objects, and inheritance

• Objects are the basic run-time entities in an object-oriented system.

• A class defines the structure of its objects.

• Classes are organized in an “is-a” hierarchy defined by inheritance.

55

Page 56: Chapter 2 Data Design and Implementation

Inheritance

1. Allows programmers to create a new class that is a specialization of an existing class.

2. The new class is called a derived class of the existing class;

• the existing class is the base class of the new class.

56

Page 57: Chapter 2 Data Design and Implementation

Inheritance

• Inheritance fosters reuse by allowing an application to take an already-tested class and derive a class from it that inherits the properties the application needs

• Polymorphism: the ability of a language to have duplicate method names in an inheritance hierarchy and to apply the method that is appropriate for the object to which the method is applied

57

Page 58: Chapter 2 Data Design and Implementation

Inheritance

• Inheritance and polymorphism combined allow the programmer to build useful hierarchies of classes that can be reused in different applications

• Mapping of problem into solution

58

Page 59: Chapter 2 Data Design and Implementation

# include <string>

class MoneyType

{

public:

void Initialize(long, long);

long DollarsAre( ) const;

long CentsAre( ) const;

private:

long dollars;

long cents;

};

59

Page 60: Chapter 2 Data Design and Implementation

class ExtMoneyType:public MoneyType{public: string CurrencyIs( ); void Initialize(long, long, const string);private: string currency;};ExtMoneyType extMoney;void ExtMoneyType::Initialize (long newDollars, long newCents, string newCurrency){ currency = newCurrency; MoneyType::Initialize(newDollars, newCents);}String ExtMoneyType::CurrencyIs() const{ return currency;

} 60

Page 61: Chapter 2 Data Design and Implementation

Exceptions

• An exception is an unusual situation that occurs when the program is running.

• Exception Management • Define the error condition• Enclose code containing possible error (try).• Alert the system if error occurs (throw).• Handle error if it is thrown (catch).

61

Page 62: Chapter 2 Data Design and Implementation

try, catch, and throw

Try{ // code that contains a possible error

… throw string(“An error has occurred in function …”);

}Catch (string message){

std::cout << message << std::endl;return 1;

}

62

Page 63: Chapter 2 Data Design and Implementation

try{ infile >> value; do { if (value < 0) throw string("Negative value"); sum = sum + value; } while (infile); } catch (string message) // Parameter of the catch is type string { // Code that handles the exception cout << message << " found in file. Program aborted." return 1; } // Code to continue processing if exception not thrown cout << "Sum of values on the file: " << sum;

Exits lo

op and goes

to catch

63

Page 64: Chapter 2 Data Design and Implementation

Namespace

namespace mySpace

{

// All variables and

// functions within this

// block must be accessed

// using scope

// resolution operator (::).

}

Purpose: Avoid namespace pollution.

64

Page 65: Chapter 2 Data Design and Implementation

Three Ways to Access Members within a Namespace

• Qualify each reference: mySpace::name with every reference.

• Using declaration: using mySpace::name;All future references to name refer to mySpace::name.

• Using directive:using namespace mySpace;All members of mySpace can be referenced without

qualification.

65

Page 66: Chapter 2 Data Design and Implementation

Rules for Use of Namespace std(within text)

• Qualify names in prototypes and/or function definitions.

• If name used more than once in a function block, use a using declaration.

• If more than one name is used from a namespace, use a using directive.

66

Page 67: Chapter 2 Data Design and Implementation

Lecture 6

Page 68: Chapter 2 Data Design and Implementation

constint const x = 5;const int x = 5;const int *p_int;int const *p_int;int * const p_int = &x;int const * const p_int = &x;

int method() const;const char * method();int method(int const *p_int);

68

x is a constant integer

a pointer to constant data

a constant pointer to data

a method that does not modify the object

a constant pointer to constant data

a method that has a constant output

a method whose parameter is constant

const int*const Method(const int*const&)const;

Page 69: Chapter 2 Data Design and Implementation

Map to Joe’s Diner

69

Page 70: Chapter 2 Data Design and Implementation

Which Cost More to Feed?

70

Page 71: Chapter 2 Data Design and Implementation

Order of Magnitude of a Function

The order of magnitude, or Big-O notation, of a function expresses the computing timeof a problem as the term in a function that increases most rapidly relative to the sizeof a problem.

71

Page 72: Chapter 2 Data Design and Implementation

Complexity

• Let us assume two algorithms A and B that solve the same class of problems.

• The time complexity of A is 5,000n, the one for B is 1.1n for an input with n elements.

• For n = 10, • A requires 50,000 steps, • but B only 3, • so B seems to be superior to A.

• For n = 1000, A requires 5,000,000 steps, • while B requires 2.51041 steps.

72

Page 73: Chapter 2 Data Design and Implementation

Complexity

• This means that algorithm B cannot be used for large inputs, while algorithm A is still feasible.

• So what is important is the growth of the complexity functions.

• The growth of time and space complexity with increasing input size n is a suitable measure for the comparison of algorithms.

73

Page 74: Chapter 2 Data Design and Implementation

Names of Orders of Magnitude

O(1) bounded (by a constant) time

O(log2N) logarithmic time

O(N) linear time

O(N*log2N) N*log2N time

O(N2) quadratic time

O(N3) cubic time

O(2N ) exponential time

74

Page 75: Chapter 2 Data Design and Implementation

N log2N N*log2N N2 2N

1 0 0 1 2

2 1 2 4 4

4 2 8 16 16

8 3 24 64 256

16 4 64 256 65,536

32 5 160 1024 4,294,967,296

64 6 384 4096 1.84*1019

128 7 896 16,384 3.40*1038

75

Page 76: Chapter 2 Data Design and Implementation

The Growth of Functions• “Popular” functions g(n) aren log n, log n, 1, 2n, n2, n!, n, n3

Listed from slowest to fastest growth:

• 1• log n• n• n log n• n2

• n3

• 2n

• n!

76

Page 77: Chapter 2 Data Design and Implementation

The Growth of Functions

• A problem that can be solved with polynomial worst-case complexity is called tractable

• Problems of higher complexity are called intractable

• Problems that no algorithm can solve are called unsolvable

77

Page 78: Chapter 2 Data Design and Implementation

Comparison of Two Algorithms

• Add all numbers from 1 to 20

78

Page 79: Chapter 2 Data Design and Implementation

Complexity Examples

What does the following algorithm compute?

int who_knows(int a[n]) {int m = 0;for {int i = 0; i<n; i++}

for {int j = i+1; j<n; j++}if ( abs(a[i] – a[j]) > m )

m = abs(a[i] – a[j]);return m;

}returns the maximum difference between any two numbers in the input arrayComparisons: n-1 + n-2 + n-3 + … + 1 = (n-1)n/2 = 0.5n2 - 0.5n

Time complexity is O(n2)

79

Page 80: Chapter 2 Data Design and Implementation

Complexity Examples

Another algorithm solving the same problem:

int max_diff(int a[n]) {int min = a[0];int max = a[0];for {int i = 1; i<n; i++}

if ( a[i] < min )min = a[i];

else if ( a[i] > max )max = a[i];

return max-min;}

Comparisons: 2n - 2

Time complexity is O(n).80

Page 81: Chapter 2 Data Design and Implementation

Find “John Smith”

81

Page 82: Chapter 2 Data Design and Implementation

Big-O Comparison of List Operations

OPERATION UnsortedList SortedList

GetItem O(N) O(N) linear search

O(log2N) binary search

PutItemFind O(1) O(log2N) searchPut O(1) O(N) moving downCombined O(1) O(N)

DeleteItemFind O(N) O(log2N) searchPut O(1) swap O(N) moving upCombined O(N) O(N)

82

Page 83: Chapter 2 Data Design and Implementation

OVERVIEW

Page 84: Chapter 2 Data Design and Implementation

Overview• The application view of a data structure is associated with which of the

following? • A. What? • B. Why? • C. How? • The implementation view of a data structure is associated with which of

the following? • A. What? • B. Why? • C. How? • The logical view of a data structure is associated with which of the

following? • A. What? • B. Why? • C. How?

84

Page 85: Chapter 2 Data Design and Implementation

OverviewThe file containing the definition of class DateType is called the ______ file.

A. specification

B. implementation

C.client

•The file containing the definitions of the member functions of class DateType is called the ______ file. •A. specification •B. implementation •C. client

85

Page 86: Chapter 2 Data Design and Implementation

Which of the following statements in a client program correctly prints out the day of the variable day1 of type DateType?

class DateType {

public:

void Initialize(int, int, int);

int GetYear() const; // returns year

int GetMonth() const; // returns month

int GetDay() const; // returns day

private:

int year;

int month;

int day;

};A. cout << day1.GetDay;

B. cout << day1.GetDay();

C. cout << GetDay.day1;

D. cout cout << GetDay(day1);

E. The day cannot be printed by a client program.

86

Page 87: Chapter 2 Data Design and Implementation

What is the minimum number of test cases needed to adequately test this program?

void CheckTriangle(int b, int c, int a)

{

if ((a == b) && (b == c))

cout << "Equalateral" << endl;

else

if (a == b)

cout << "Isoscelese" << endl;

else

cout << "Scalene" << endl;

}

687

Page 88: Chapter 2 Data Design and Implementation

True / False

• We can protect an array that is sent to a function by using const

• C++ ensures we do not write beyond allocated array slots.

• The position of an element in a one dimensional array associated with Index is Address(Index) = Base + Index * SizeOfElement

• In a two dimensional array, component selection is as follows

table[columnIndex][rowIndex]

88

Page 89: Chapter 2 Data Design and Implementation

True / False

• Members of a struct are public by default.

• Members of a class are public by default.

• A struct differs from an array in that its elements need not occupy a consecutive block of memory cells.

• C++ provides a way to sequentially iterate through the fields in a struct.

89

Page 90: Chapter 2 Data Design and Implementation

True / False

• Exceptions must be handled within the function in which they occur.

• Exceptions cannot be handled within the block in which they occur.

• Code that can cause an exception should be enclosed within a try clause.

• Exception handlers are enclosed within a catch clause.

• C++ does have built-in exceptions.

90

Page 91: Chapter 2 Data Design and Implementation

True / False

• Each try/catch statement can have only one catch clause.

• It is the responsibility of the client code to handle all exceptions.

• using myNames::GetData is a using declaration.

• using namespace myName is a using directive.

91

Page 92: Chapter 2 Data Design and Implementation

True / False

• Polymorphism has the ability to determine which function to call for a particular object.

• Inheritance is a language mechanism by which one class acquires data and operations of another class.

• Composition is a mechanism by which an internal data member of one class is defined to be an object of another class type.

92

is-a

has-a

Page 93: Chapter 2 Data Design and Implementation

True / False• Static binding refers to compile-time binding

• Dynamic binding refers to run-time binding

• In C++, a derived class's constructor is executed before the base class constructor is executed.

93


Recommended