1 Chapter 4 ADT Sorted List. 2 Sorted Type Class Interface Diagram SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem.

Slides:



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

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
6-1 Chapter Goals Determine whether a problem is suitable for a computer solution Describe the computer problem-solving process and relate it to Polya’s.
Informática II Prof. Dr. Gustavo Patiño MJ
1 C++ Plus Data Structures Nell Dale Chapter 1 Software Engineering Principles.
CS Data Structures Chapter 8 Lists Mehmet H Gunes
Chapter 4 ADT Sorted List.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Algorithms and Problem Solving-1 Algorithms and Problem Solving Mainly based on Chapter 6: “Problem Solving and Algorithm Design” from the Book: “Computer.
Algorithms and Problem Solving-1 Algorithms and Problem Solving.
Algorithms and Problem Solving
Programming with Recursion
Algorithms and Problem Solving. Learn about problem solving skills Explore the algorithmic approach for problem solving Learn about algorithm development.
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.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
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.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
Chapter 3 ADT Unsorted List. Lecture 7 List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
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.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 9 Searching Arrays.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
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 Recall Definition of Stack l Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
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.
Chapter 9 slide 1 Introduction to Search Algorithms Search: locate an item in a list (array, vector, table, etc.) of information Two algorithms (methods):
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 Data Structures and Algorithms Stacks and Queues.
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 Nell Dale Lecture 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta.
CSI 1340 Introduction to Computer Science II Chapter 3 ADTs Unsorted List and Sorted List.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Chapter 5 (Part 1) ADT Stack 1 Fall Stacks TOP OF THE STACK.
1 C++ Plus Data Structures Abstract Data Types Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by.
Chapter 14 Dynamic Data and Linked Lists
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
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Object-Oriented Design
C++ Plus Data Structures
Chapter 15 Pointers, Dynamic Data, and Reference Types
Unsorted Lists CS3240, L. Grewe.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 16 Linked Structures
C++ Plus Data Structures
CSI 1340 Introduction to Computer Science II
Yan Shi CS/SE 2630 Lecture Notes
Data Structures and Algorithms Memory allocation and Dynamic Array
Presentation transcript:

1 Chapter 4 ADT Sorted List

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

3 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

4 InsertItem algorithm forSortedList 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.

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

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

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

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

9 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 < length; index++ ) info [ index - 1 ] = info [ index ] ; length-- ; } 9

10 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] 11

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

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

14 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

15 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

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

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

18 Allocation of memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time. DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new.

19 3 Kinds of Program Data STATIC DATA: memory allocation exists throughout execution of program. static long SeedValue; AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function. DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using unary operators new and delete

Using operator new If memory is available in an area called the free store (or heap), operator new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. Otherwise, the null pointer 0 is returned. The dynamically allocated object exists until the delete operator destroys it. 20

ptr Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; std::cout << *ptr;

22 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; std::cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr

23 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; std::cout << *ptr; NOTE: Dynamic data has no variable name 2000 ptr ‘B’

24 Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; std::cout << *ptr; delete ptr; 2000 ptr NOTE: Delete deallocates the memory pointed to by ptr. ?

The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. The memory is returned to the free store. Square brackets are used with delete to deallocate a dynamically allocated array of classes. Using operator delete 25

Some C++ pointer operations Precedence Higher -> Select member of class pointed to Unary: ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate + - Add Subtract >= Relational operators == != Tests for equality, inequality Lower = Assignment

27 Dynamic Array Allocation char *ptr; // ptr is a pointer variable that // can hold the address of a char ptr = new char[ 5 ]; // dynamically, during run time, allocates // memory for 5 characters and places into // the contents of ptr their beginning address ptr 6000

28 Dynamic Array Allocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; // a pointer can be subscripted std::cout << ptr[ 2] ; ptr 6000 ‘B’ ‘y’ ‘e’ ‘\0’ ‘u’

29 Dynamic Array Deallocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; delete ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated, but // the value of ptr is considered unassigned ptr ?

30 int* ptr = new int; *ptr = 3; ptr = new int; // changes value of ptr *ptr = 4; What happens here? 3 ptr 3 ptr 4

31 Memory Leak A memory leak occurs when dynamic memory (that was created using operator new ) has been left without a pointer to it by the programmer, and so is inaccessible. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; How else can an object become inaccessible? 8 ptr -5 ptr2

32 Causing a Memory Leak int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible 8 ptr -5 ptr2 8 ptr -5 ptr2

33 occurs when two pointers point to the same object and delete is applied to one of them. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; A Dangling Pointer 8 ptr -5 ptr2 FOR EXAMPLE,

34 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; Leaving a Dangling Pointer 8 ptr -5 ptr2 8 ptr NULL ptr2

35 DYNAMIC ARRAY IMPLEMENTATION StackType ~StackType Push Pop. class StackType Private Data: top 2 maxStack 5 items items [0] items [1] items [2] items [3] items [4]

36 // StackType class template template class StackType { public: StackType(int max ); // max is stack size StackType();// Default size is 500 // Rest of the prototypes go here. private: int top; int maxStack; // Maximum number of stack items. ItemType* items; // Pointer to dynamically // allocated memory }; 36

37 // Templated StackType class variables declared StackType myStack(100); // Stack of at most 100 integers. StackType yourStack(50); // Stack of at most 50 floating point values. StackType aStack; // Stack of at most 500 characters.

38 // Implementation of member function templates template StackType ::StackType(int max) { maxStack = max; top = -1; items = new ItemType[maxStack]; } template StackType ::StackType() { maxStack = 500; top = -1; items = new ItemType[max]; } 38

39 InsertItem algorithm for Sorted Linked List Find proper position for the new element in the sorted list using two pointers predLoc and location, where predLoc trails behind location. Obtain a node for insertion and place item in it. Insert the node by adjusting pointers. Increment length.

40 Implementing SortedType member function InsertItem // LINKED LIST IMPLEMENTATION (sorted.cpp) #include “ItemType.h” template 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. // Post: item is in the list. List is still sorted. {. }

41 The Inchworm Effect

42 Inserting ‘S’ into a Sorted List ‘C’ ‘L’ ‘X’ Private data: length 3 listData currentPos ? predLoc location moreToSearch

43 Finding proper position for ‘S’ ‘C’ ‘L’ ‘X’ Private data: length 3 listData currentPos ? predLoc location NULL moreToSearch true

44 Finding proper position for ‘S’ ‘C’ ‘L’ ‘X’ Private data: length 3 listData currentPos ? predLoc location moreToSearch true

45 Finding Proper Position for ‘S’ ‘C’ ‘L’ ‘X’ Private data: length 3 listData currentPos ? predLoc location moreToSearch false

46 Inserting ‘S’ into Proper Position ‘C’ ‘L’ ‘X’ Private data: length 4 listData currentPos predLoc location moreToSearch false ‘S’

47 Object-Oriented Design Methodology Four stages to the decomposition process Brainstorming Filtering Scenarios Responsibility algorithms

48 Brainstorming A group problem-solving technique that involves the spontaneous contribution of ideas from all members of the group All ideas are potential good ideas Think fast and furiously first, and ponder later A little humor can be a powerful force Brainstorming is designed to produce a list of candidate classes

49 Filtering Determine which are the core classes in the problem solution There may be two classes in the list that have many common attributes and behaviors There may be classes that really don’t belong in the problem solution

50 Scenarios Simulate class interactions Ask “What if?” questions Assign responsibilities to each class There are two types of responsibilities What a class must know about itself (knowledge) What a class must be able to do (behavior)

51 Responsibility Algorithms The algorithms must be written for the responsibilities Knowledge responsibilities usually just return the contents of one of an object’s variables Action responsibilities are a little more complicated, often involving calculations

52 Computer Example Let’s repeat the problem-solving process for creating an address list Brainstorming and filtering Circling the nouns and underlining the verbs

53 Computer Example First pass at a list of classes

54 Computer Example Filtered list

55 CRC Cards

56 Responsibility Algorithms