Chapter 4 ADT Sorted List.

Slides:



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

DATA STRUCTURES USING C++ Chapter 5
Computer Science and Software Engineering University of Wisconsin - Platteville 5. LinkedList Yan Shi CS/SE 2630 Lecture Notes.
Lists + CS3240, L. Grewe 1. 2 Goals Use the C++ template mechanism fr defining generic data types Implement a circular linked list Implement a linked.
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.
CS Data Structures Chapter 8 Lists Mehmet H Gunes
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
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.
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.
Doubly Linked Lists CS 308 – Data Structures. Node data info: the user's data next, back: the address of the next and previous node in the list.back.next.info.
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.
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 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.
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.
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.
3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has.
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.
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 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.
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.
CSI 1340 Introduction to Computer Science II Chapter 3 ADTs Unsorted List and Sorted List.
1 What is a Circular Linked List? l A circular linked list is a list in which every node has a successor; the “last” element is succeeded by the “first”
1 Chapter 4 ADT Sorted List. 2 Sorted Type Class Interface Diagram SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem.
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 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Chapter 5 (Part 1) ADT Stack 1 Fall Stacks TOP OF THE STACK.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 17: Linked Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
Chapter 14 Dynamic Data and Linked Lists
Chapter 16: 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
CS Data Structures Chapter 8 Lists Mehmet H Gunes
C++ Plus Data Structures
Chapter 16-2 Linked Structures
C++ Plus Data Structures
Chapter 4 Link Based Implementations
Unsorted Lists CS3240, L. Grewe.
Chapter 16 Linked Structures
C++ Plus Data 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
Presentation transcript:

Chapter 4 ADT Sorted List

Sorted Type Class Interface Diagram MakeEmpty Private data: length info [ 0 ] [ 1 ] [ 2 ] [MAX_ITEMS-1] currentPos IsFull GetLength GetItem PutItem DeleteItem ResetList GetNextItem 2

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? PutItem DeleteItem 3

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

Implementing SortedType member function PutItem // IMPLEMENTATION FILE (sorted.cpp) #include “itemtype.h” // also must appear in client code void SortedType :: PutItem ( 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. { . } 5

void SortedType :: PutItem ( 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++; } } // make room for new element in sorted list for ( int index = length ; index > location ; index-- ) info [ index ] = info [ index - 1 ]; info [ location ] = item; length++; 6

DeleteItem algorithm for SortedList ADT Find the location of the element to be deleted from the sorted list. Eliminate space occupied by the item by moving up all the list elements that follow it. Decrement length. 7

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

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

Improving member function GetItem 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? 10

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

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

13 ItemType SortedType::GetItem ( 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 is returned; otherwise, // original item is returned. { 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 } 13

Trace of Binary Search item = 45 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 15 26 38 57 62 78 84 91 108 119 info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] first midPoint last GREATER first = midPoint + 1 14

Trace continued item = 45 info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 first, last midPoint GREATER first = midPoint + 1 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 15

Trace concludes item = 45 info[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] 15 26 38 57 62 78 84 91 108 119 last first first > last found = false 16

17 ItemType SortedType::GetItem ( 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; case EQUAL : found = true ; item = info[ midPoint ]; } }return item; 17

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

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 19

Arrays created at run time If memory is available in an area called the free store (or heap), operator new allocates memory for the object or array and returns the address of (pointer to) the memory allocated. Otherwise, the NULL pointer 0 is returned. The dynamically allocated object exists until the delete operator destroys it. 20

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 6000 6000 ptr 21

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

class SortedType<char> Private data: length 3 listData currentPos ? MakeEmpty ~SortedType ‘C’ ‘L’ ‘X’ RetrieveItem InsertItem DeleteItem . GetNextItem 23 23

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

The Inchworm Effect 25

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

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

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

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

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

Why is a destructor needed? When a local list variable goes out of scope, the memory space for data member listPtr is deallocated. But the nodes to which listPtr points are not deallocated. A class destructor is used to deallocate the dynamic memory pointed to by the data member. 31 31

Implementing the Destructor SortedType::~SortedType() // Post: List is empty; all items have // been deallocated. { NodeType* tempPtr; while (listData != NULL) tempPtr = listData; listData = listData->next; delete tempPtr; } 32

How do the SortedList implementations compare? 33

SortedList implementations comparison 34

List implementations comparison

Chapter 6 Lists Plus

What is a Circular Linked List? A circular linked list is a list in which every node has a successor; the “last” element is succeeded by the “first” element.

External Pointer to the Last Node

What is a Doubly Linked List? A doubly linked list is a list in which each node is linked to both its successor and its predecessor.

Linking the New Node into the List

Deleting from a Doubly Linked List What are the advantages of a circular doubly linked list?

What are Header and Trailer Nodes? A Header Node is a node at the beginning of a list that contains a key value smaller than any possible key. A Trailer Node is a node at the end of a list that contains a key larger than any possible key. Both header and trailer are placeholding nodes used to simplify list processing.

A linked list in static storage ? A Linked List as an Array of Records

A Sorted list Stored in an Array of Nodes

An Array with Linked List of Values and Free Space

An Array with Three Lists (Including the Free List)

Overview

Overview Inserting into an unsorted list and inserting into a sorted list are the same time complexity. In a sorted list, there is a semantic relationship between successive items in the list. Deleting from a sorted array based list requires that the elements below the one being deleted be moved up one slot. Searching an unsorted list and a sorted list are always the same time complexity. You can perform a binary search on both a linked and an array-based implementation of a sorted list. To dynamically allocate an array-based list there should be a parameterized constructor.

Overview the order of the operation that determines if an item is in a list in a sorted, array-based implementation a list in an unsorted, array-based implementation a list in a sorted, linked implementation a list in an unsorted, linked implementation O(log N) O(N) O(N) O(N)

Overview location < length moreToSearch location < length false // Pre: List contains valid data and List is sorted by key using function // ComparedTo. // There is at most one list item with the same key as item; there may be none. // Post: No list element has the same key as item. List is still sorted. void SortedType::DeleteItem(ItemType item) { int location = 0; int index; bool moreToSearch; moreToSearch = ____________________; bool found = false; while ( !found && _______________) switch (item.ComparedTo(info[location])) { case LESS : location++; break; case GREATER : moreToSearch = _____________________; case EQUAL : ________ = true; } if (found) { for (index = location + 1; index < length; index++) info[index - 1] = ______________; length--; location < length moreToSearch location < length false found info[index]

Overview EQUAL index < length length-- // Pre: List contains valid data, sorted by key values. // One and only one list item with the same key as item's is in the list. // Post: No list element has the same key as item; the list is still sorted. void SortedType::DeleteItem(ItemType item) { int location = 0; while (item.ComparedTo(info[location]) != ___________) location++; for (int index = location + 1; ________________; index++) info[index - 1] = info[index]; ___________; } EQUAL index < length length--

Overview length - 1 first <= last midPoint - 1 midPoint + 1 ItemType SortedType::GetItem(ItemType& item, bool& found) { // Uses binary search algorithm int midPoint; int first =______________; int last = ______________; bool moreToSearch = _______________; found = false; while (moreToSearch && !found) { midPoint = (first + last) / 2; switch (item.ComparedTo(info[midPoint])) { case LESS : last = _______________; moreToSearch = first <= last; break; case GREATER : first = _______________; moreToSearch = first <= last; case EQUAL : found = true; item =_________________; } return item; length - 1 first <= last midPoint - 1 midPoint + 1 info[midPoint]