Download - ADT Unsorted List - storm.cis.fordham.edu
Fall 2013 CISC2200 Yanjun Li 1
ADT Unsorted List
Chapter 3
Fall 2013 CISC2200 Yanjun Li 2
Outline
• Unsorted List
• Array-based Implementation
• Linked Implementation
• Comparison
Fall 2013 CISC2200 Yanjun Li 3
Lists
• Linear relationship– Each element except the first has a unique predecessor, and each element except the last has a unique successor
• Length – The number of items in a list; the length can vary over time
• Unsorted list– A list in which data items are placed in no particular order; the only relationships between data elements are the list predecessor and successor relationships
Fall 2013 CISC2200 Yanjun Li 4
Lists
• Sorted list
– A list that is sorted by the value in the key; there is a semantic relationship among the keys of the items in the list
• Key
– The attributes that are used to determine the logical order of the list
Name some possible keys
Fall 2013 CISC2200 Yanjun Li 5
ADT Unsorted List
• Logical Level
• Abstract Data Type (ADT)– A data type whose properties (domain and operations) are specified independently of any particular implementation
Can you think of what operations we
should provide for our ADT Unsorted List?
Fall 2013 CISC2200 Yanjun Li 6
ADT Unsorted List
• Transformers– MakeEmpty
– InsertItem
– DeleteItem
• Observers– IsFull
– GetLength
– RetrieveItem
• Iterators– ResetList
– GetNextItem
change state
observe state
process all
Fall 2013 CISC2200 Yanjun Li 7
ADT Unsorted List
• Client is responsible for error checking.
– Precondition of each function enforces it.
– Provide clients the tools with which to check
for the conditions.
• Observers
Fall 2013 CISC2200 Yanjun Li 8
ADT Unsorted List
• Generic data type
– A type for which the operations are defined but the
types of the items being manipulated are not defined
– How can we make the items on the list generic?
– List items are of class ItemType, which has a
ComparedTo function that returns LESS, GREATER,
EQUAL
• ComparedTo function compares the keys of items.
Fall 2013 CISC2200 Yanjun Li 9
// SPECIFICATION FILE ItemType.h #ifndef ITEMTYPE_H#define ITEMTYPE_H
const int MAX_ITEM = 5;enum RelationType { LESS, EQUAL, GREATER };
class ItemType // declares class data type{public : // 4 public member functions
ItemType(){}RelationType ComparedTo( ItemType ) const{..}void Print( ) const{..}void Initialize( int value ){…}
private : // 1 private data memberint value; // could be any type
} ;#endif
Class ItemType
Fall 2013 CISC2200 Yanjun Li 10
ADT Unsorted List
• Implementation Level
Two implementations
// SPECIFICATION FILE ( UnsortedType.h )#include “ItemType.h”
class UnsortedType // declares a class data type{public :
UnsortedType();
void MakeEmpty( ); // 8 public member functionsbool IsFull( ) const;bool IsEmpty( ) const; int GetLength( ) const; // returns length of listvoid RetrieveItem( ItemType& item, bool& found );void InsertItem( ItemType item ); void DeleteItem( ItemType item ); void ResetList( );void GetNextItem( ItemType& item );
Public declarations are the same for either
implementation; only private data changes
What is
ItemType?
Fall 2013 CISC2200 Yanjun Li 12
Array-Based Implementation Private data members for array-based
implementation
private :private :private :private :
intintintint length; length; length; length;
ItemTypeItemTypeItemTypeItemType info[MAX_ITEMSinfo[MAX_ITEMSinfo[MAX_ITEMSinfo[MAX_ITEMS]; ]; ]; ];
intintintint currentPoscurrentPoscurrentPoscurrentPos;;;;
};};};};
Where does
MAX_ITEMS come from?
Fall 2013 CISC2200 Yanjun Li 13
Array-Based Implementation
Notice the
difference
between
the array
and the
list stored
in the array
Array-based
implementation
The array ends at the slot with index
MAX_ITEMS – 1 ; the list ends in the slot
with index length - 1
Fall 2013 CISC2200 Yanjun Li 14
ADT Unsorted List
• Constructor– A special member function of a class that is implicitly
invoked when a class object is defined
UnsortedTypeUnsortedTypeUnsortedTypeUnsortedType();();();();
• What should the constructor do?
UnsortedType::UnsortedType()
{
length = 0;
}
15
• What is a full list? An empty list?//pre: List has been initialized//post: function value = (list is full)
bool UnsortedType::IsFull() const{
return (length == MAX_ITEM);}
//pre: List has been initialized//post: function value = (list is empty)
bool UnsortedType:: IsEmpty() const{
return (length == 0);}
Array-Based Implementation
Fall 2013 CISC2200 Yanjun Li 16
//pre: List has been initialized
//post:
int UnsortedType::GetLength() const
{
return length ;
}
Fall 2013 CISC2200 Yanjun Li 17
Array-Based Implementation
length 3
info [ 0 ] Maxwell
[ 1 ] Bradley
[ 2 ] Asad
[ 3 ]
.
.
.
[MAX_ITEMS-1]
If the list is unsorted,
where should the
next element go
?
insert("Hsing");
Fall 2013 CISC2200 Yanjun Li 18
Array-Based Implementation
length 4
info [ 0 ] Maxwell
[ 1 ] Bradley
[ 2 ] Asad
[ 3 ] Hsing.
.
[MAX_ITEMS-1]
That was
easy!
Can you
code it
?
Fall 2013 CISC2200 Yanjun Li 19
Array-Based Implementation
//pre: List has been initialized. List is not // full, item is not in list.// Post: item is in the list.
void UnsortedType::InsertItem(ItemType item)
{info[length] = item;length++;
}
Fall 2013 CISC2200 Yanjun Li 20
Array-Based Implementation
How would you go about finding an item in the list?
• Cycle through the list looking for the item
What are the two ending cases?
• The item is found
• The item is not in the list
How do we compare items?
We use function ComparedToComparedToComparedToComparedTo in class ItemTypeItemTypeItemTypeItemType
(compare keys of items)(compare keys of items)(compare keys of items)(compare keys of items)
Fall 2013 CISC2200 Yanjun Li 21
Array-Based Implementation
// Pre: Key member(s) 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 isunchanged.
void UnsortedType::RetrieveItem(ItemType& item, bool& found){
found = false;for ( int location =0; location <length; location ++){
if (item.ComparedTo(info[location]) == EQUAL){
item = info[location];found = true;break;
}}
}
Fall 2013 CISC2200 Yanjun Li 22
Array-Based ImplementationHow do you delete an item?
First you find the item
Yes, but how do you delete it?
• Move those below it up on slot
• Replace it with another item
* Tips: This is an unsorted list.
What other item?
How about the item at info[length-1] ?
Fall 2013 CISC2200 Yanjun Li 23
Array-Based Implementation
// Pre: item// Pre: item// Pre: item// Pre: item’’’’s key has been s key has been s key has been s key has been inititalizedinititalizedinititalizedinititalized....
//////// One and only one element in the list has a key that One and only one element in the list has a key that One and only one element in the list has a key that One and only one element in the list has a key that
// // // // matches itemmatches itemmatches itemmatches item’’’’s.s.s.s.
// Post: No element in the list has a key that matches item// Post: No element in the list has a key that matches item// Post: No element in the list has a key that matches item// Post: No element in the list has a key that matches item’’’’s.s.s.s.void UnsortedType::DeleteItem ( ItemType item )
{
int location = 0 ;
while (item.ComparedTo (info[location]) != EQUAL)
location++;
// move last element into position where item was located// move last element into position where item was located// move last element into position where item was located// move last element into position where item was located
info [location] = info [length - 1 ] ;
length-- ; //the length of the list is decreased//the length of the list is decreased//the length of the list is decreased//the length of the list is decreased
}
Fall 2013 CISC2200 Yanjun Li 24
Array-Based Implementation
location: 0
length 4
info [ 0 ] Maxwell
[ 1 ] Bradley
[ 2 ] Asad
[ 3 ] Hsing.
.
.
[MAX_ITEMS-1]
Delete Bradley
Fall 2013 CISC2200 Yanjun Li 25
Array-Based Implementation
location: 1
Key Bradley has
been matched
length 4
info [ 0 ] Maxwell
[ 1 ] Bradley
[ 2 ] Asad
[ 3 ] Hsing.
.
.
[MAX_ITEMS-1]
Fall 2013 CISC2200 Yanjun Li 26
Array-Based Implementation
location: 1
length 3
info [ 0 ] Maxwell
[ 1 ] Hsing
[ 2 ] Asad
[ 3 ] Hsing.
.
.
[MAX_ITEMS-1]
Copy of last list element
is in the position where
the key Bradley
was before; length has
been decremented
Fall 2013 CISC2200 Yanjun Li 27
Array-Based Implementation
• Only when there is a matched element in
the list, we could perform this function.
• What will happen if the matching element
is the last element ?
• What will happen if there is only one
element in the list ?
• What if the elements are pointers and they
points to dynamically allocated memory ?
Fall 2013 CISC2200 Yanjun Li 28
Array-Based Implementation
// Pre: N/A // Pre: N/A // Pre: N/A // Pre: N/A
// Post: the list is empty// Post: the list is empty// Post: the list is empty// Post: the list is empty
void UnsortedType::MakeEmpty()
{
length = 0;
}
• We do not have to do anything to the array that holds the list items to make a list empty. What if the elements are pointers and they points to dynamically allocated memory ?
// Pre: List has been inititalized.// Post: Current position is prior to first element.void UnsortedType::ResetList ( ) { currentPos = -1 ;
}// Pre: List has been initialized. Current position is // defined. // Element at current position is not last in list.Element at current position is not last in list.Element at current position is not last in list.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.void UnsortedType::GetNextItem(ItemType& item) {currentPos++ ;item = info [currentPos] ;
}
29
Array-Based Implementation
Iterators
Fall 2013 CISC2200 Yanjun Li 30
Array-Based Implementation
• Application Level
• How to use the List implemented?
– PrintList(UnsortedType&)
• Users do not need to know how the list is
implemented.
Fall 2013 CISC2200 Yanjun Li 31
Testing Array-Based Implementation// Pre: list has been initialized. // Pre: list has been initialized. // Pre: list has been initialized. // Pre: list has been initialized. ////////// Post: Each component in list has been written. // Post: Each component in list has been written. // Post: Each component in list has been written. // Post: Each component in list has been written. // // // // void PrintList(UnsortedType & list){int length;ItemType item;
list.ResetListlist.ResetListlist.ResetListlist.ResetList( );( );( );( );length = list.GetLength( );for (int counter = 1; counter <= length; counter++){
list.GetNextItem(itemlist.GetNextItem(itemlist.GetNextItem(itemlist.GetNextItem(item););););item.Print();
}}
Fall 2013 CISC2200 Yanjun Li 32
Test Plan
• Testing Strategy
– Combination of black-box and clear-box.
– Black-box : test precondition & post-condition.
– Clear-box : test the code inside the functions,
try path testing.
• Values for testing
– End cases.
Fall 2013 CISC2200 Yanjun Li 33
Data Encapsulation
• Information internal to the implementation
of the Unsorted List ADT.
– Private data members
• The array info[ ]info[ ]info[ ]info[ ]
• The index of the iterator currentPoscurrentPoscurrentPoscurrentPos
– Local variable locationlocationlocationlocation, which contains the
array index of the list item being processed.
Fall 2013 CISC2200 Yanjun Li 34
Linked Implementation
Fall 2013 CISC2200 Yanjun Li 35
class NodeTypeNodeTypeNodeTypeNodeType
#include “ItemType.h”
class NodeType{
public:
ItemType info;
NodeType * next;
};
Fall 2013 CISC2200 Yanjun Li 36
Linked Implementation
• Private data for the Unsorted List ADT, linked-list implementation
private:NodeType *listData;int length;NodeType *currentPos;
};
List with two items
Fall 2013 CISC2200 Yanjun Li 37
Linked Implementation
Be sure
you
understand
the
differences
among
locationlocationlocationlocation,*location*location*location*location, and
locationlocationlocationlocation---->info>info>info>info
NodeType * location;
Fall 2013 CISC2200 Yanjun Li 38
Linked Implementation
Remember the design notation?
Node(location)Node(location)Node(location)Node(location) *location*location*location*location
Info(location)Info(location)Info(location)Info(location) locationlocationlocationlocation---->info>info>info>info
Next(location)Next(location)Next(location)Next(location) locationlocationlocationlocation---->next>next>next>next
How do you set locationlocationlocationlocation to Next(locationNext(locationNext(locationNext(location))))?
How do you set Info(location)Info(location)Info(location)Info(location) to valuevaluevaluevalue?
Fall 2013 CISC2200 Yanjun Li 39
// SPECIFICATION FILE ( UnsortedType.h )#include “ItemType.h”
class NodeType {public:ItemType info;NodeType *next;
};
class UnsortedType // declares a class data type{public : UnsortedType();~UnsortedType();void MakeEmpty( ); // 8 public member functionsbool IsFull( ) const;bool IsEmpty( ) const; int GetLength( ) const; // returns length of listvoid RetrieveItem( ItemType& item, bool& found );void InsertItem( ItemType item ); void DeleteItem( ItemType item ); void ResetList( );void GetNextItem( ItemType& item );
Fall 2013 CISC2200 Yanjun Li 40
Linked Implementation
How do you know that a linked list is empty?
– listDatalistDatalistDatalistData is NULLNULLNULLNULL
What should the constructor do?
– Set lengthlengthlengthlength to 0000
– Set listDatalistDatalistDatalistData to NULLNULLNULLNULL
What about currentPoscurrentPoscurrentPoscurrentPos?
– We let ResetListResetListResetListResetList()()()() take care of initializing
currentPoscurrentPoscurrentPoscurrentPosYou write the constructor
Fall 2013 CISC2200 Yanjun Li 41
Linked Implementation
What about the observers IsFull() and GetLength() ?
GetLength() just returns length
Can a linked list ever be full?
Yes, if you run out of memory
Ask for a new node within a try/catch
Fall 2013 CISC2200 Yanjun Li 42
Linked Implementation
bool Unsortedtype::IsFull() const
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch (std::bad_alloc e)
{
return true;
}
}
Fall 2013 CISC2200 Yanjun Li 43
Linked Implementation
Initialize location to position of first item
Set found to false
Set moreToSearch to (have not examined Info(last))
while moreToSearch AND NOT found
switch (item.ComparedTo(Info(location)))
case LESS :
case GREATER :
Set location to Next(location)
Set moreToSearch to (have not examined Info(last))
case EQUAL :
Set found to true
Set item to Info(location)
RetrieveItem( )
Fall 2013 CISC2200 Yanjun Li 44
// Pre: Key member of item is initialized.// Pre: Key member of item is initialized.// Pre: Key member of item is initialized.// Pre: Key member of item is initialized.// Post: If found, item// Post: If found, item// Post: If found, item// Post: If found, item’’’’s key matches an elements key matches an elements key matches an elements key matches an element’’’’s key in the list and a copy of thats key in the list and a copy of thats key in the list and a copy of thats key in the list and a copy of that// element has been stored in item; otherwise, item is unchanged// element has been stored in item; otherwise, item is unchanged// element has been stored in item; otherwise, item is unchanged// element has been stored in item; otherwise, item is unchanged....
void void void void UnsortedType::RetrieveItemUnsortedType::RetrieveItemUnsortedType::RetrieveItemUnsortedType::RetrieveItem( ( ( ( ItemTypeItemTypeItemTypeItemType& item, & item, & item, & item, boolboolboolbool& found ) & found ) & found ) & found ) { { { {
boolboolboolbool moreToSearchmoreToSearchmoreToSearchmoreToSearch;;;;NodeTypeNodeTypeNodeTypeNodeType* location = * location = * location = * location = listDatalistDatalistDatalistData;;;;found = false ;found = false ;found = false ;found = false ;moreToSearchmoreToSearchmoreToSearchmoreToSearch = ( location != NULL ) ;= ( location != NULL ) ;= ( location != NULL ) ;= ( location != NULL ) ;while ( while ( while ( while ( moreToSearchmoreToSearchmoreToSearchmoreToSearch && !found ) && !found ) && !found ) && !found ) { { { {
if ( if ( if ( if ( item.ComparedTo(locationitem.ComparedTo(locationitem.ComparedTo(locationitem.ComparedTo(location---->info ) == EQUAL) >info ) == EQUAL) >info ) == EQUAL) >info ) == EQUAL) // match here// match here// match here// match here{ { { {
found = true;found = true;found = true;found = true; item = locationitem = locationitem = locationitem = location---->info;>info;>info;>info;}}}}elseelseelseelse // advance pointer// advance pointer// advance pointer// advance pointer{ { { {
location = locationlocation = locationlocation = locationlocation = location---->next; >next; >next; >next; moreToSearchmoreToSearchmoreToSearchmoreToSearch = ( location != NULL );= ( location != NULL );= ( location != NULL );= ( location != NULL );
} } } } } } } }
}}}}
Linked Implementation
Fall 2013 CISC2200 Yanjun Li 45
Linked Implmentation
Fall 2013 CISC2200 Yanjun Li 4646
Linked Implementation
How do we go about building a linked list?
Create a list of one item
1. Get a node using newnewnewnew
location = new ocation = new ocation = new ocation = new NodeTypeNodeTypeNodeTypeNodeType;;;;
2. Put value into info portion of node
locationlocationlocationlocation---->info = item;>info = item;>info = item;>info = item;
3. Put pointer to node in external pointer
listDatalistDatalistDatalistData = location;= location;= location;= location;
Fall 2013 CISC2200 Yanjun Li 4747
Linked Implementation
We forgot something: We must put NULLNULLNULLNULLin the Next position of the first node
LocationLocationLocationLocation---->next=NULL;>next=NULL;>next=NULL;>next=NULL;
Fall 2013 CISC2200 Yanjun Li 48
Linked Implementation
How do we add a node to our list?
1. Get a node using newnewnewnew
location = new location = new location = new location = new NodeTypeNodeTypeNodeTypeNodeType;;;;
2. Put value into info portion
locationlocationlocationlocation---->info = Item;>info = Item;>info = Item;>info = Item;
3. Put node into list …
Where? Where should the node go?
Does it matter?
Fall 2013 CISC2200 Yanjun Li 49
Linked Implementation
Now we must put the two parts together--carefully!
Fall 2013 CISC2200 Yanjun Li 50
Liked Implementation
These
steps
must be
done in
this
order!
Why?
Fall 2013 CISC2200 Yanjun Li 51
Linked Implementation
// Pre: list is not full and item is not in list.
// Post: item is in the list; length has been incremented.
void UnsortedType::InsertItem ( ItemType item )
{
NodeType * location;
// obtain and fill a node
location = new NodeType;
location->info = item;
location->next = listData;
listData = location;
length++;
}
Where is the item inserted? Head or End?
Why?
Fall 2013 CISC2200 Yanjun Li 52
Linked Implementation
How do you delete an item from the list?
1. Find the item
2. Remove the item
Fall 2013 CISC2200 Yanjun Li 53
Linked ImplementationNodeType* location = listData;NodeType* tempLocation;// Find the item// Find the item// Find the item// Find the item
if (item.ComparedTo(listData->info) == EQUAL) { // item in first location// item in first location// item in first location// item in first location
tempLocation = location;listData = listData->next; //move the head of the list//move the head of the list//move the head of the list//move the head of the list
}else{ while (item.ComparedTo((location->next)->info) != EQUAL)
location = location->next;tempLocation = location->next;location->next = (location ->next)->next;//remove the middle one, connect the two ends//remove the middle one, connect the two ends//remove the middle one, connect the two ends//remove the middle one, connect the two ends
}delete tempLocation;length--; Pre: the item is in the list!!
Fall 2013 CISC2200 Yanjun Li 54
Linked Implementation
void UnsortedType::MakeEmpty()
{
NodeType *tempPtr;
while (listData != NULL)
{
tempPtr = listData;
listData = listData->next;
delete tempPtr;
}
length = 0;
}
Why can we just set
listData to NULL?
‘D’
‘E’
‘H’
listData
tempPtr
‘H’
Length=0;
Fall 2013 CISC2200 Yanjun Li 55
Linked Implementation
ResetListResetListResetListResetList()()()() and GetNextItemGetNextItemGetNextItemGetNextItem()()()()
What was currentPoscurrentPoscurrentPoscurrentPos in the array-
based implementation?
What would be the equivalent in a
linked implementation?
Fall 2013 CISC2200 Yanjun Li 56
Linked Implementation
void UnsortedType::ResetList(){
currentPos = NULL;}
void UnsortedType::GetNextItem(ItemType& item){
if (currentPos == NULL)currentPos = listData;
elsecurrentPos = currentPos->next;
item = currentPos->info;}
What is the Precondition & Postcondition on GetNextItem ?
Fall 2013 CISC2200 Yanjun Li 57
Class Destructors
• Recall: listData is deallocated when it
goes out of scope but what listDatalistDatalistDatalistDatapoints to is not deallocated
• Class Destructor
– A function that is implicitly called when class
object goes out of scope
~UnsortedType(); // Destructor// Destructor// Destructor// Destructor
What must this function do?
Have we done a similar job?
Fall 2013 CISC2200 Yanjun Li 58
Which One Is Better ?
• Array-based Or Linked List?
• How to Compare them?
how much our implementation costs us
in terms of time, memory space !
Fall 2013 CISC2200 Yanjun Li 59
Algorithm Growth Rates
• An algorithm’s time requirements can be
measured as a function of the problem size N
– Number of nodes in a linked list
– Size of an array
• Algorithm’s growth rate: enables comparison of
one algorithm with another
• Algorithm efficiency is typically a concern for
large problems only
Fall 2013 CISC2200 Yanjun Li 60
The Story of Big O
Big O (order of magnitude) is a measure of the
“worst-case” scenario for a given algorithm
taking in input of size N.
Mathematically:
Given an input of size N (where N is really really
really big), what is the asymptotic upper bounds
of the algorithm in terms of time/space (how long
will it take to execute/how much memory will it
require)?
Fall 2013 CISC2200 Yanjun Li 61
Algorithm Growth Rates
Figure 9-1 Time requirements as a function of the problem size n
• Algorithm A requires time proportional to n2
• Algorithm B requires time proportional to n
Fall 2013 CISC2200 Yanjun Li 62
O(?)
There are a few common notations for Big-O. These
are categories into which almost all algorithms fit into
(once we throw away all the garbage and reduce the
algorithm to its purest form). These are denoted as
follows:
•O(1)
•O(log2 N)
•O(N)
•O(N M)
•O(M N)
•Or some combination
of these.
Fall 2013 CISC2200 Yanjun Li 63
O(1): What A Dream!
• O(1) doesn’t mean
– we finish everything in one second or one
CPU cycle
– use one-element array or linked list
• We just wish that it did
Fall 2013 CISC2200 Yanjun Li 64
O(1): What It Is About
• O(1) means constant time or space. No
matter what we throw at a particular
algorithm, we know EXACTLY how
long/how much it will take to execute the
program:
– Given an array of size N (where N is
unknown), access a particular value.
– Given a list of size P (where P is unknown),
retrieve the first element of the list.
Fall 2013 CISC2200 Yanjun Li 65
O(N): Linear time/space
• This one’s pretty easy to see.
• If we have a list containing N elements,
and we are searching for a particular value
that isn’t even contained in the list, how
many elements do we have to search
through?
N elements!
Fall 2013 CISC2200 Yanjun Li 66
Space
• how much memory space is needed:
– Array-based: max. size of the array. O(NMax.)
– Linked-List: number of elements actually in
the list at run time . O(n)
• However, each node element of linked list
is larger than array element because the
pointer to next member is stored as well.
Fall 2013 CISC2200 Yanjun Li 67
Time
Which array-based operations are O(1)?
Which linked operations are O(1)?
Which array-based operations are O(N)?
Which linked operations are O(N)?
Can you say which implementation is better?
Fall 2013 CISC2200 Yanjun Li 68
Time - O(1)
• Array-based
– IsFull()
– GetLength()
– IsEmpty()
– InsertItem()
– MakeEmpty()
– ResetList()
– GetNextItem()
• Linked
– IsFull()
– GetLength()
– IsEmpty()
– InsertItem()
– ResetList()
– GetNextItem()
Fall 2013 CISC2200 Yanjun Li 69
Time – O(N)
• Array-based
– RetrieveItem()
– DeleteItem()
• Linked
– RetrieveItem()
– DeleteItem()
– MakeEmpty()
Fall 2013 CISC2200 Yanjun Li 70
Reference
• Reproduced from C++ Plus Data
Structures, 4th edition by Nell Dale.
• Reproduced by permission of Jones
and Bartlett Publishers International.