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

Slides:



Advertisements
Similar presentations
Sorted Lists CS Data Structures Sections 4.1, 4.2 & 4.3.
Advertisements

Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
ADTs unsorted List and Sorted List
Computer Science and Software Engineering University of Wisconsin - Platteville 5. LinkedList Yan Shi CS/SE 2630 Lecture Notes.
Chapter 3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element except the.
C++ Plus Data Structures ADTs Unsorted List and Sorted List
Unsorted Lists CS 308 – Data Structures. What is a list? A list is a homogeneous collection of elements. Linear relationship between elements: (1) Each.
1 C++ Plus Data Structures Nell Dale Chapter 1 Software Engineering Principles.
Chapter 4 ADT Sorted List.
Sorted Lists CS Data Structures. Sorted List Specification (partial) InsertItem (ItemType item) Function: Adds item to list Preconditions: (1) List.
1 Nell Dale Chapter 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
C++ Plus Data Structures
1 Chapter 6 Object-Oriented Software Development.
Searching Arrays Linear search Binary search small arrays
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Dynamic Structures & Arrays.
1 Fall Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List.
Implementing a Sorted List as a Linked Structure CS 308 – Data Structures.
Data Structures Using C++ 2E
Chapter 4 ADT Sorted List.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Applied Arrays: Lists and Strings. 2 Chapter 13 Topics  Meaning of a List  Insertion and Deletion of List Elements  Selection Sort of List Elements.
Chapter 3 ADT Unsorted List. Lecture 7 List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element.
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
What is a Stack? n Logical (or ADT) level: A stack is an ordered group of homogeneous items in which the removal and addition of items can take place only.
Linked List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has a unique.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List operations.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 9 Searching Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 9 slide 1 Introduction to Search Algorithms Search: locate an item in a list (array, vector, table, etc.) of information Two algorithms (methods):
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 4 ADT Sorted List. Sorted Type Class Interface Diagram SortedType class IsFull GetLength ResetList DeleteItem PutItem MakeEmpty GetItem Private.
What is a List? A list is a homogeneous collection of elements, with a linear relationship between elements. Each list element (except the first) has a.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
1 Chapter 13 Applied Arrays: Lists and Strings Dale/Weems/Headington.
CS 302 – Data Structures Sections 3.1, 3.2, 3.4 & 3.5
1 Nell Dale Lecture 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
1 Chapter 4 ADT Sorted List. 2 Sorted Type Class Interface Diagram SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
CSI 1340 Introduction to Computer Science II Chapter 6 Lists Plus.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Chapter 16: Linked Lists.
C++ Programming:. Program Design Including
Chapter 13 Applied Arrays: Lists and Strings
C++ Plus Data Structures ADTs Unsorted List and Sorted List
TA: Nouf Al-Harbi Data Structures LAB 3 TA: Nouf Al-Harbi
C++ Plus Data Structures
C++ Plus Data Structures
Unsorted Lists CS3240, L. Grewe.
C++ Plus Data Structures
Chapter 16 Linked Structures
CSI 1340 Introduction to Computer Science II
Chapter 13 Applied Arrays: Lists and Strings
Yan Shi CS/SE 2630 Lecture Notes
Data Structures and Algorithms Memory allocation and Dynamic Array
TA: Nouf Al-Harbi Data Structures LAB 2 TA: Nouf Al-Harbi
Presentation transcript:

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

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

// 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];

class SalesPerson { public: void SetSales(int month, float amount); float GetSales(int month) const; private: float sales[12]; }; C++ Class - salesperson.h

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

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]; }

Show how the SalesPerson class can be utilized in a program (Main.cpp) to: (1) set the sales figure for month 1 to $ (2) set the sales figure for month 2 to $ (3) display the following: Sales for month 1 = $

C++ Program- main.cpp #include #include “salesperson.h” using namespace std; int main( ) { SalesPerson s; s.SetSales(1, ); s.SetSales(2, ); cout << “Sales for month 1 = $“ << s.GetSales(1) << endl; return 0; }

Class Constructors

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

Do we still need a public member function that assigns values to the private member variables if we include a constructor?

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!!

Show the implementation for a default constructor for the SalesPerson class

SalesPerson::SalesPerson( ) { for (i = 0; i < 12; i++) sales[i] = 0.0; } Default Constructor for SalesPerson

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

Determines how values are copied from one object to another. Consists of two operators: Assignment operator Copy constructor Determining Class Value

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

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 use Time y(x); Time y = x; // Not assignment because y is created Time y = Time(x); Copy Constructor

Assignment operator Assigns the values of one object to another object. Copy Constructor Used whenever a new object is created and initialized to an existing object of the same type. Assignment vs. Copy Constructor

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++

Testing the Copy Constructor

#include #include “time.h” using namespace std; int main( ) { Time t; t.setTime(13,37,6); Time s(t);// May generate a fatal error t.printStandard( ); s.printStandard( ); return 0; } Testing the Copy Constructor

Creating Your Own Copy Constructor

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)

#include “time.h” Time::Time(const Time& w) { hour = w.hour; minute = w.minute; second = w.second; } Copy Constructor Implementation File (time.cpp)

Testing the Assignment Operator (=)

#include #include “time.h” using namespace std; int main( ) { Time t; t.setTime(13,37,6); Time s; s = t;// May generate a fatal error t.printStandard( ); s.printStandard( ); return 0; } Assignment Operator (=) Use in Main.cpp

Overloading the Assignment Operator (=)

class Time { public: Time( );... void operator=(const Time& w); private: int hour; int minute; int second; } Assignment Operator (=) Header File (time.h)

#include “time.h” void Time::operator=(const Time& w) { hour = w.hour; minute = w.minute; second = w.second; } Assignment Operator (=) Implementation File (time.cpp)

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.

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).

ADT Unsorted List Operations Transformers – MakeEmpty – InsertItem – DeleteItem Observers – IsFull – LengthIs – RetrieveItem Iterators – ResetList – GetNextItem change state observe state process all

// 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 list void 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 ; ItemTypeinfo[MAX_ITEMS] ; intcurrentPos ; } ;

Class Interface Diagram UnsortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem GetNextItem Private data: length info [ 0 ] [ 1 ] [ 2 ] [MAX_ITEMS-1] currentPos

// 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++ ; }

Before Inserting Hsing into an Unsorted List length 3 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ]. [MAX_ITEMS-1] The item will be placed into the length location, and length will be incremented.

After Inserting Hsing into an Unsorted List length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1]

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 ) ; }

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 ; }

Retrieving Ivan from an Unsorted List moreToSearch: true found: false location: 0 length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1]

Retrieving Ivan from an Unsorted List length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] moreToSearch: true found: false location: 1

Retrieving Ivan from an Unsorted List length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] moreToSearch: true found: false location: 2

Retrieving Ivan from an Unsorted List length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] moreToSearch: true found: false location: 3

Retrieving Ivan from an Unsorted List length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] moreToSearch: false found: false location: 4

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-- ; }

Deleting Bradley from an Unsorted List location: 0 length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] Key Bradley has not been matched.

Deleting Bradley from an Unsorted List location: 1 length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] Key Bradley has been matched.

Deleting Bradley from an Unsorted List location: 1 length 4 info [ 0 ] Maxwell [ 1 ] Hsing [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] Placed copy of last list element into the position where the key Bradley was before.

Deleting Bradley from an Unsorted List location: 1 length 3 info [ 0 ] Maxwell [ 1 ] Hsing [ 2 ] Asad [ 3 ] Hsing. [MAX_ITEMS-1] Decremented length.

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] ; }

// 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 RelationTypeComparedTo ( ItemType ) const ; voidPrint ( ) const ; void Initialize ( int number ) ; private : // 1 private data member int value ; // could be any different type } ; Specifying class ItemType

// IMPLEMENTATION FILE( itemtype.cpp ) // Implementation depends on the data type of value. #include “itemtype.h” #include 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 ; }

Private data value ComparedTo Print Initialize class ItemType ItemType Class Interface Diagram

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

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

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.

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. {. }

void SortedType :: InsertItem ( ItemType item ) { bool moreToSearch ; int location = 0 ; // find proper location for new element moreToSearch = ( 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++ ; }

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.

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. {. }

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 -- ; }

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?

Retrieving Eliot from a Sorted List The sequential search for Eliot can stop when Hsing has been examined. length 4 info [ 0 ] Asad [ 1 ] Bradley [ 2 ] Hsing [ 3 ] Maxwell. [MAX_ITEMS-1]

Binary Seach in a Sorted List Examines 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.

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; intlast = 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 }

Trace of Binary Search info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] item = 45 first midPoint last info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first midPoint last LESS last = midPoint - 1 GREATERfirst = midPoint + 1

Trace continued info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] item = 45 first, midPoint, last info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first, last midPoint LESS last = midPoint - 1GREATERfirst = midPoint + 1

Trace concludes info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] item = 45 last first first > last found = false

void SortedType::RetrieveItem ( ItemType& item, bool& found ) // ASSUMES info ARRAY SORTED IN ASCENDING ORDER { int midPoint ; int first = 0; intlast = 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 ; }

Order of Magnitude of a Function The order of magnitude, or Big-O notation, of a function expresses the computing time of a problem as the term in a function that increases most rapidly relative to the size of a problem.

Big-O of Two Functions for (count = 1; count <= n; count++) sum += count; sum = ((n + 1) * 2) / 2; O(N) O(1)

Names of Orders of Magnitude O(1) bounded (by a constant) time O(log 2 N) logarithmic time O(N) linear time O(N*log 2 N) N*log 2 N time O(N 2 ) quadratic time O( 2 N ) exponential time

N log 2 N N*log 2 N N 2 2 N , ,294,967, ,384 5 years supercomputing

Comparison of List Operations OPERATION UnsortedList SortedList RetrieveItem O(N) O(N) linear search O(log 2 N) binary search InsertItem Find O(1) O(N) search Put O(1) O(N) moving down Combined O(1) O(N) DeleteItem Find O(N) O(N) search Put O(1) swap O(N) moving up Combined O(N) O(N)