75
CSI 1340 Introduction to Computer Science II Chapter 3 ADTs Unsorted List and Sorted List

CSI 1340 Introduction to Computer Science II

  • Upload
    taline

  • View
    31

  • Download
    0

Embed Size (px)

DESCRIPTION

CSI 1340 Introduction to Computer Science II. Chapter 3 ADTs Unsorted List and Sorted List. Self-test. Create a class called SalesPerson that includes 2 public member functions: void SetSales(int month, float amount); float GetSales(int month) const; And 1 private member variable: - PowerPoint PPT Presentation

Citation preview

Page 1: CSI 1340 Introduction to Computer Science II

CSI 1340Introduction to Computer Science II

Chapter 3ADTs Unsorted List and Sorted List

Page 2: CSI 1340 Introduction to Computer Science II

Create a class called SalesPerson that includes 2 public member functions:

void SetSales(int month, float amount);

float GetSales(int month) const;

And 1 private member variable:float sales[12];

Self-test

Page 3: CSI 1340 Introduction to Computer Science II

// FILE: salesperson.h// CLASS PROVIDED: SalesPerson (an ADT for a SalesPerson)// Modification member function// void SetSales(int month, float amount);// Precondition: 1 <= month <= 12; amount has been // assigned a floating point value.// Postcondition: The sales figure for the month indicated // by month has been assigned amount.// Constant member function// float GetSales(int month) const;// Precondition: 1 <= month <= 12// Postcondition: The sales figure for the month indicated // by month has been returned. // Private member variable// float sales[12];

Page 4: CSI 1340 Introduction to Computer Science II

class SalesPerson

{

public:

void SetSales(int month, float amount);

float GetSales(int month) const;

private:

float sales[12];

};

C++ Class - salesperson.h

Page 5: CSI 1340 Introduction to Computer Science II

Create a correct C++ implementation file (.cpp) for the SalesPerson class

Page 6: CSI 1340 Introduction to Computer Science II

C++ Implementation - salesperson.cpp

#include “salesperson.h” void SalesPerson::SetSales(int month, float amount){

sales[month - 1] = amount;}float SalesPerson::GetSales(int month) const{

return sales[month - 1];}

Page 7: CSI 1340 Introduction to Computer Science II

Show how the SalesPerson class can be utilized in a program (Main.cpp) to:

(1) set the sales figure for month 1 to $1500.00(2) set the sales figure for month 2 to $1000.00(3) display the following:

Sales for month 1 = $1500.00

Page 8: CSI 1340 Introduction to Computer Science II

C++ Program- main.cpp

#include <iostream>#include “salesperson.h”using namespace std;int main( ) {

SalesPerson s;s.SetSales(1, 1500.00);s.SetSales(2, 1000.00);cout << “Sales for month 1 = $“ << s.GetSales(1)

<< endl;return 0;

}

Page 9: CSI 1340 Introduction to Computer Science II

Class Constructors

Page 10: CSI 1340 Introduction to Computer Science II

You may declare as many constructors as you like--one for each different way of initializing an object.

Each constructor must have a distinct parameter list so that the compiler can tell them apart.

Only one default constructor is allowed.

Rules for Constructors

Page 11: CSI 1340 Introduction to Computer Science II

Do we still need a public member function that assigns values to the

private member variables if we include a constructor?

Page 12: CSI 1340 Introduction to Computer Science II

Public member functions can be called at any time by the user.

A constructor (either the default or an alternative) is utilized only once, when an object is declared. It cannot be called by the user.

Yes!!

Page 13: CSI 1340 Introduction to Computer Science II

Show the implementation for a default constructor for the SalesPerson class

Page 14: CSI 1340 Introduction to Computer Science II

SalesPerson::SalesPerson( )

{

for (i = 0; i < 12; i++)

sales[i] = 0.0;

}

Default Constructor for SalesPerson

Page 15: CSI 1340 Introduction to Computer Science II

Function Overloading: Creating several variants of the same function, distinguishing only by parameter types

Operator Overloading: Gives a new definition for an existing operator (i.e., =, = =, +, +=, . . .)

Often used to define new meanings for operators of a class.

Overloading

Page 16: CSI 1340 Introduction to Computer Science II

Determines how values are copied from one object to another.

Consists of two operators:Assignment operatorCopy constructor

Determining Class Value

Page 17: CSI 1340 Introduction to Computer Science II

y = x copies the value of x to y.For a class, assignment should be carried out by

copying the value of each private member variable from class x to class y.

Assignment Operator

Page 18: CSI 1340 Introduction to Computer Science II

Initializes a new object as an exact copy of an existing object.

The copy constructor is a constructor with exactly one parameter, and the data type of the parameter is the same as the constructor class, e.g., Time(const Time& w);

Examples of its useTime y(x);

Time y = x; // Not assignment because y is created

Time y = Time(x);

Copy Constructor

Page 19: CSI 1340 Introduction to Computer Science II

Assignment operatorAssigns the values of one object to another object.

Copy ConstructorUsed whenever a new object is created and initialized to

an existing object of the same type.

Assignment vs. Copy Constructor

Page 20: CSI 1340 Introduction to Computer Science II

C++ provides an automatic assignment operator and an automatic copy constructor.

For some classes, the automatic versions fail and programmers must either write their own or indicate that the value semantics are not safe to use.

Assignment Operator & Copy Constructor in C++

Page 21: CSI 1340 Introduction to Computer Science II

Testing the Copy Constructor

Page 22: CSI 1340 Introduction to Computer Science II

#include <iostream>#include “time.h”using namespace std;int main( ){

Time t;t.setTime(13,37,6);Time s(t); // May generate a fatal errort.printStandard( );s.printStandard( );return 0;

}

Testing the Copy Constructor

Page 23: CSI 1340 Introduction to Computer Science II

Creating Your Own Copy Constructor

Page 24: CSI 1340 Introduction to Computer Science II

class Time{public:

Time( );Time(int hr,int min,int sec);Time(const Time& w);. . .

private:int hour;int minute;int second;

}

Copy Constructor Header File (time.h)

Page 25: CSI 1340 Introduction to Computer Science II

#include “time.h”

Time::Time(const Time& w)

{

hour = w.hour;

minute = w.minute;

second = w.second;

}

Copy Constructor Implementation File (time.cpp)

Page 26: CSI 1340 Introduction to Computer Science II

Testing the Assignment Operator (=)

Page 27: CSI 1340 Introduction to Computer Science II

#include <iostream>#include “time.h”using namespace std;int main( ){

Time t;t.setTime(13,37,6);Time s;s = t; // May generate a fatal errort.printStandard( );s.printStandard( );return 0;

}

Assignment Operator (=) Use in Main.cpp

Page 28: CSI 1340 Introduction to Computer Science II

Overloading theAssignment Operator (=)

Page 29: CSI 1340 Introduction to Computer Science II

class Time{public:

Time( );. . .void operator=(const Time& w);

private:int hour;int minute;int second;

}

Assignment Operator (=) Header File (time.h)

Page 30: CSI 1340 Introduction to Computer Science II

#include “time.h”

void Time::operator=(const Time& w)

{

hour = w.hour;

minute = w.minute;

second = w.second;

}

Assignment Operator (=) Implementation File (time.cpp)

Page 31: CSI 1340 Introduction to Computer Science II

What is a List?

A list is a homogeneous collection of elements, with a linear relationship between elements.

That is, each list element (except the first) has a unique predecessor, and each element (except the last) has a unique successor.

Page 32: CSI 1340 Introduction to Computer Science II

Sorted and Unsorted Lists

UNSORTED LIST

Elements are placed into the list in no particular order.

SORTED LIST

List elements are in an order that is sorted in some way -- either numerically or alphabetically by the elements themselves, or by a component of the element (called a KEY member) .

Page 33: CSI 1340 Introduction to Computer Science II

ADT Unsorted List OperationsTransformers

– MakeEmpty – InsertItem – DeleteItem

Observers – IsFull– LengthIs– RetrieveItem

Iterators – ResetList – GetNextItem

change state

observe state

process all

Page 34: CSI 1340 Introduction to Computer Science II

// SPECIFICATION FILE ( unsorted.h )#include “ItemType.h”

class UnsortedType // declares a class data type{public : // 8 public member functions

void MakeEmpty ( ) ;bool IsFull ( ) const ; int LengthIs ( ) const ; // returns length of listvoid RetrieveItem ( ItemType& item, bool& found ) ;void InsertItem ( ItemType item ) ; void DeleteItem ( ItemType item ) ; void ResetList ( );void GetNextItem ( ItemType& item ) ;

private : // 3 private data members

int length ; ItemType info[MAX_ITEMS] ; int currentPos ;

} ;

Page 35: CSI 1340 Introduction to Computer Science II

Class Interface Diagram

UnsortedType class

IsFull

LengthIs

ResetList

DeleteItem

InsertItem

MakeEmpty

RetrieveItem

GetNextItem

Private data:

length

info [ 0 ] [ 1 ] [ 2 ]

[MAX_ITEMS-1]

currentPos

Page 36: CSI 1340 Introduction to Computer Science II

// IMPLEMENTATION FILE ARRAY-BASED LIST ( unsorted.cpp )#include “itemtype.h”

void UnsortedType::MakeEmpty ( ) // Pre: None.// Post: List is empty.{

length = 0 ;}

void UnsortedType::InsertItem ( ItemType item )// Pre: List has been initialized. List is not full. Item is not in list.// Post: item is in the list.{

info[length] = item ;length++ ;

}

Page 37: CSI 1340 Introduction to Computer Science II

Before Inserting Hsing into anUnsorted List

length 3

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] .

. .

[MAX_ITEMS-1]

The item willbe placed intothe length location,and length will beincremented.

Page 38: CSI 1340 Introduction to Computer Science II

After Inserting Hsing into anUnsorted List

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Page 39: CSI 1340 Introduction to Computer Science II

void UnsortedType::LengthIs ( ) const// Pre: List has been inititalized.// Post: Function value == ( number of elements in list ).{

return length ;}

bool UnsortedType::IsFull ( ) const// Pre: List has been initialized.// Post: Function value == ( list is full ).{

return ( length == MAX_ITEMS ) ;}

Page 40: CSI 1340 Introduction to Computer Science II

void UnsortedType::RetrieveItem ( ItemType& item, bool& found ) { bool moreToSearch ;

int location = 0 ;

found = false ;moreToSearch = ( location < length ) ;while ( moreToSearch && !found ){

switch ( item.ComparedTo( info[location] ) ) { case LESS :

case GREATER : location++ ; moreToSearch = ( location < length ) ;

break; case EQUAL : found = true ;

item = info[ location ] ;break ;

} }}

Page 41: CSI 1340 Introduction to Computer Science II

Retrieving Ivan from anUnsorted List

moreToSearch: true

found: false

location: 0

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Page 42: CSI 1340 Introduction to Computer Science II

Retrieving Ivan from anUnsorted List

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

moreToSearch: true

found: false

location: 1

Page 43: CSI 1340 Introduction to Computer Science II

Retrieving Ivan from anUnsorted List

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

moreToSearch: true

found: false

location: 2

Page 44: CSI 1340 Introduction to Computer Science II

Retrieving Ivan from anUnsorted List

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

moreToSearch: true

found: false

location: 3

Page 45: CSI 1340 Introduction to Computer Science II

Retrieving Ivan from anUnsorted List

length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

moreToSearch: false

found: false

location: 4

Page 46: CSI 1340 Introduction to Computer Science II

void UnsortedType::DeleteItem ( ItemType item ) // Pre: item’s key has been inititalized.// An element in the list has a key that matches item’s.// Post: No element in the list has a key that matches item’s.{

int location = 0 ; while (item.ComparedTo (info [location] ) != EQUAL )

location++;

// move last element into position where item was located

info [location] = info [length - 1 ] ;length-- ;

}

Page 47: CSI 1340 Introduction to Computer Science II

Deleting Bradley from anUnsorted List

location: 0 length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Key Bradley hasnot been matched.

Page 48: CSI 1340 Introduction to Computer Science II

Deleting Bradley from anUnsorted List

location: 1 length 4

info [ 0 ] Maxwell

[ 1 ] Bradley

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Key Bradley hasbeen matched.

Page 49: CSI 1340 Introduction to Computer Science II

Deleting Bradley from anUnsorted List

location: 1 length 4

info [ 0 ] Maxwell

[ 1 ] Hsing

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Placed copy oflast list elementinto the position where the key Bradley was before.

Page 50: CSI 1340 Introduction to Computer Science II

Deleting Bradley from anUnsorted List

location: 1 length 3

info [ 0 ] Maxwell

[ 1 ] Hsing

[ 2 ] Asad

[ 3 ] Hsing .

. .

[MAX_ITEMS-1]

Decremented length.

Page 51: CSI 1340 Introduction to Computer Science II

void UnsortedType::ResetList ( ) // Pre: List has been inititalized.// Post: Current position is prior to first element in list.{

currentPos = -1 ;}

void UnsortedType::GetNextItem ( ItemType& item ) // Pre: List has been initialized. Current position is defined.// Element at current position is not last in list.// Post: Current position is updated to next position.// item is a copy of element at current position.{

currentPos++ ;item = info [currentPos] ;

}

Page 52: CSI 1340 Introduction to Computer Science II

// SPECIFICATION FILE ( itemtype.h )

const int MAX_ITEM = 5 ;enum RelationType { LESS, EQUAL, GREATER } ;

class ItemType // declares class data type{public : // 3 public member functions

RelationType ComparedTo ( ItemType ) const ; void Print ( ) const ;

void Initialize ( int number ) ;

private : // 1 private data memberint value ; // could be any different type

} ;

Specifying class ItemType

Page 53: CSI 1340 Introduction to Computer Science II

// IMPLEMENTATION FILE ( itemtype.cpp )// Implementation depends on the data type of value.

#include “itemtype.h”#include <iostream.h>

RelationType ComparedTo ( ItemType otherItem ) const {

if ( value < otherItem.value )return LESS ;

else if ( value > otherItem.value )return GREATER ;

else return EQUAL ;}

void Print ( ) const {

cout << value << endl ;}

void Initialize ( int number ){

value = number ; }

Page 54: CSI 1340 Introduction to Computer Science II

Private data

value

ComparedTo

Print

Initialize

class ItemType

ItemType Class Interface Diagram

Page 55: CSI 1340 Introduction to Computer Science II

SortedType Class Interface Diagram

SortedType class

IsFull

LengthIs

ResetList

DeleteItem

InsertItem

MakeEmpty

RetrieveItem

Private data:

length

info [ 0 ] [ 1 ] [ 2 ]

[MAX_ITEMS-1]

currentPos

GetNextItem

Page 56: CSI 1340 Introduction to Computer Science II

Member functions

Which member function specifications and implementations must change to ensure that any instance of the Sorted List ADT remains sorted at all times?

– InsertItem

– DeleteItem

Page 57: CSI 1340 Introduction to Computer Science II

InsertItem algorithm for SortedList ADT

Find proper location for the new element in the sorted list.

Create space for the new element by moving down all the list elements that will follow it.

Put the new element in the list.

Increment length.

Page 58: CSI 1340 Introduction to Computer Science II

Implementing SortedType member function InsertItem

// IMPLEMENTATION FILE (sorted.cpp)

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

void SortedType :: InsertItem ( ItemType item )

// Pre: List has been initialized. List is not full. item is not in list.

// List is sorted by key member using function ComparedTo.

// Post: item is in the list. List is still sorted.{

.

.

.

}

Page 59: CSI 1340 Introduction to Computer Science II

void SortedType :: InsertItem ( ItemType item ){ bool moreToSearch ; int location = 0 ;

// find proper location for new elementmoreToSearch = ( location < length ) ;while ( moreToSearch ){ switch ( item.ComparedTo( info[location] ) )

{ case LESS : moreToSearch = false ; break ;

case GREATER : location++ ; moreToSearch = ( location < length ) ; break ;

} } // make room for new element in sorted list

for ( int index = length ; index > location ; index-- )info [ index ] = info [ index - 1 ] ;

info [ location ] = item ; length++ ;}

Page 60: CSI 1340 Introduction to Computer Science II

DeleteItem algorithm for SortedList ADT

Find the location of the element to be deleted from the sorted list.

Eliminate space occupied by the item being deleted by moving up all the list elements that follow it.

Decrement length.

Page 61: CSI 1340 Introduction to Computer Science II

Implementing SortedType member function DeleteItem

// IMPLEMENTATION FILE continued (sorted.cpp)

void SortedType :: DeleteItem ( ItemType item )

// Pre: List has been initialized. Key member of item is initialized.

// Exactly one element in list has a key matching item’s key.

// List is sorted by key member using function ComparedTo.

// Post: No item in list has key matching item’s key.

// List is still sorted.{

.

.

.

}

Page 62: CSI 1340 Introduction to Computer Science II

void SortedType :: DeleteItem ( ItemType item ){ int location = 0 ;

// find location of element to be deleted

while ( item.ComparedTo ( info[location] ) != EQUAL )location++ ;

// move up elements that follow deleted item in sorted list

for ( int index = location + 1 ; index < location ; index++ )info [ index - 1 ] = info [ index ] ;

length-- ;}

Page 63: CSI 1340 Introduction to Computer Science II

Improving member function RetrieveItem

Recall that with the Unsorted List ADT

we examined each list element beginning

with info[ 0 ], until we either found a

matching key, or we had examined all

the elements in the Unsorted List.

How can the searching algorithm be improved for Sorted List ADT?

Page 64: CSI 1340 Introduction to Computer Science II

Retrieving Eliot from aSorted List

The sequential search for Eliot can stop when Hsing has beenexamined.

length 4

info [ 0 ] Asad

[ 1 ] Bradley

[ 2 ] Hsing

[ 3 ] Maxwell .

. .

[MAX_ITEMS-1]

Page 65: CSI 1340 Introduction to Computer Science II

Binary Seach in a Sorted ListExamines the element in the middle of the array. Is it

the sought item? If so, stop searching. Is the middle element too small? Then start looking in second half of array. Is the middle element too large? Then begin looking in first half of the array.

Repeat the process in the half of the list that should be examined next.

Stop when item is found, or when there is nowhere else to look and item has not been found.

Page 66: CSI 1340 Introduction to Computer Science II

void SortedType::RetrieveItem ( ItemType& item, bool& found ) // Pre: Key member of item is initialized.// Post: If found, item’s key matches an element’s key in the list and a copy // of that element has been stored in item; otherwise, item is unchanged.{ int midPoint ;

int first = 0; int last = length - 1 ;

bool moreToSearch = ( first <= last ) ;

found = false ;while ( moreToSearch && !found ){ midPoint = ( first + last ) / 2 ; // INDEX OF MIDDLE ELEMENT

switch ( item.ComparedTo( info [ midPoint ] ) ) {

case LESS : . . . // LOOK IN FIRST HALF NEXT case GREATER : . . . // LOOK IN SECOND HALF NEXT case EQUAL : . . . // ITEM HAS BEEN FOUND

} }}

Page 67: CSI 1340 Introduction to Computer Science II

Trace of Binary Search

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

15 26 38 57 62 78 84 91 108 119

item = 45

first midPoint last

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

15 26 38 57 62 78 84 91 108 119

first midPoint last

LESS last = midPoint - 1

GREATER first = midPoint + 1

Page 68: CSI 1340 Introduction to Computer Science II

Trace continued

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

15 26 38 57 62 78 84 91 108 119

item = 45

first, midPoint, last

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

15 26 38 57 62 78 84 91 108 119

first, last midPoint

LESS last = midPoint - 1

GREATER first = midPoint + 1

Page 69: CSI 1340 Introduction to Computer Science II

Trace concludes

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

15 26 38 57 62 78 84 91 108 119

item = 45

last first

first > last found = false

Page 70: CSI 1340 Introduction to Computer Science II

void SortedType::RetrieveItem ( ItemType& item, bool& found ) // ASSUMES info ARRAY SORTED IN ASCENDING ORDER

{ int midPoint ;

int first = 0;

int last = length - 1 ;

bool moreToSearch = ( first <= last ) ;

found = false ;

while ( moreToSearch && !found )

{ midPoint = ( first + last ) / 2 ;

switch ( item.ComparedTo( info [ midPoint ] ) )

{ case LESS : last = midPoint - 1 ;

moreToSearch = ( first <= last ) ;

break ;

case GREATER : first = midPoint + 1 ;

moreToSearch = ( first <= last ) ;

break ;

case EQUAL : found = true ;

item = info[ midPoint ] ;

break ;

}

}

}

Page 71: CSI 1340 Introduction to Computer Science II

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.

Page 72: CSI 1340 Introduction to Computer Science II

Big-O of Two Functions

for (count = 1; count <= n; count++)sum += count;

sum = ((n + 1) * 2) / 2;

O(N)

O(1)

Page 73: CSI 1340 Introduction to Computer Science II

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( 2N ) exponential time

Page 74: CSI 1340 Introduction to Computer Science II

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

128 7 896 16,384

5 yearssupercomputing

Page 75: CSI 1340 Introduction to Computer Science II

Comparison of List Operations

OPERATION UnsortedList SortedList

RetrieveItem O(N) O(N) linear search O(log2N) binary search

InsertItemFind O(1) O(N) searchPut O(1) O(N) moving downCombined O(1) O(N)

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