Chapter09 - Chapter 9: Abstract Data Types and Algorithms...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 9: Abstract Data Types and Algorithms Algorithms Two keys to making computer software that works well: • • Organize data so it can be accessed and processed Organize efficiently. e evelop algorithms that take advantage of the Dfficiently. Develop strengths of the programming language and the hardware to accomplish what the program is attempting to do. to Chapter 9 Abstract Data Abstract Types and Algorithms Algorithms Page 1 Page Iteration Iteration When an algorithm involves repetitive actions, iteration (i.e., When iteration looping) may be a practical approach. looping) Pseudocode to implement the search for a specific name in an Pseudocode alphabetized phonebook: alphabetized Procedure SeqSearch(phonebook, sought_name) sought_name Set test_name to first name in phonebook test_name phonebook While (test_name is alphabetically before While sought_name AND sought_name there are still more names in phonebook) Do phonebook Set test_name to the next name in phonebook test_name phonebook If test_name is sought_name test_name sought_name Then return the corresponding phone number Then Notice that this algorithm always starts at messageof the phonebook list Notice Else return “Unlisted” the top Else and checks each name against sought_name until it either locates it or (if sought_name it’s not in the phonebook) passes it. it’s Chapter 9 Abstract Data Abstract Types and Algorithms Algorithms Page 2 Page Calling SeqSearch(phonebook, sought_name) where sought_name where sought_name is “Rubeus Hagrid” and phonebook is the list sought_name phonebook below: below: Name Black, Sirius Chang, Cho Dumbledore, Dumbledore, Albus Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Granger, Hermione Hermione Hagrid, Rubeus Lockhart, Lockhart, Gilderoy Gilderoy Longbottom, Longbottom, Neville Neville Malfoy, Draco McGonagall, McGonagall, Minerva Minerva Pettigrew, Peter Pomfrey, Poppy Number 5557458 5550131 5553589 5551119 5553783 5559927 5552728 5551317 5551201 555- test_name is Sirius Black, so iterate again test_name is Cho Chang, so iterate again test_name is Albus Dumbledore, so iterate again test_name is Dudley Dursley, so iterate again test_name is Argus Filch, so iterate again test_name is Cornelius Fudge, so iterate again test_name is Hermione Granger, so iterate again test_name is Rubeus Hagrid, so return 555-1317 Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 3 Page Recursion Another common approach in algorithms is to employ Another recursion (i.e., “divide and conquer”), which repeatedly recursion reduces the size of a problem until it becomes manageable. reduces Pseudocode to recursively take a base number to a specified power: Pseudocode recursively Procedure Exponentiate(base, power) power If base is 0 base Then return 0 Then Else If power < 0 power Then return Exponentiate(base, Then power+1)/base power Else If power is 0 power Then return 1 Then Else return base * Exponentiate(base, base Notice that this algorithm returns 0 if the value of base is 0, 1 if the Notice base power-1) power value of power is 0, base if the value of power is 1, 1/base if the value power base power of power is -1, and so on. power Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 4 Page A Recursive Search Algorithm Pseudocode to recursively implement the search for a Pseudocode recursively specific name in an alphabetized phonebook: specific Procedure BinarySearch(phonebook, sought_name) sought_name Set test_name to the middle name in phonebook test_name phonebook If test_name is sought_name test_name sought_name Then return corresponding phone number Then Else If phonebook has only one remaining entry phonebook Then return “Unlisted” message Then If test_name is alphabetically before sought_name test_name sought_name Then apply BinarySearch to the portion of phonebook after phonebook test_name test_name Else apply BinarySearch to the portion of phonebook before phonebook test_name t otice Nest_name this algorithm starts at the middle of the phonebook list, and Notice that keeps splitting what’s left of the phonebook in half until it either locates sought_name or runs out of names to check. sought_name Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 5 Page Calling BinarySearch(phonebook, sought_name) where sought_name where sought_name is “Rubeus Hagrid” and phonebook is the list sought_name phonebook below: below: Name Black, Sirius Chang, Cho Dumbledore, Dumbledore, Albus Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Granger, Hermione Hermione Hagrid, Rubeus Lockhart, Lockhart, Gilderoy Gilderoy Longbottom, Longbottom, Neville Neville Malfoy, Draco McGonagall, McGonagall, Minerva Minerva Pettigrew, Peter Pomfrey, Poppy Number 5557458 5550131 5553589 5551119 5553783 5559927 5552728 5551317 5551201 555- test_name is Dudley Dursley, so iterate again test_name is Cornelius Fudge, so iterate again test_name is Hermione Granger, so iterate again test_name is Rubeus Hagrid, so return 555-1317 test_name is Gilderoy Lockhart, so iterate again Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 6 Page Data Structures When interrelated information is stored in a computer’s When memory, it is usually convenient for the programmer (and for the computer’s memory management) to keep this data in a structured format. structured However, in the computer’s RAM, However, space for 100 integers has been allocated something like this: allocated Addres s An array is an indexed list An of values of the same type. of Example: int IQlist[100]; 00 01 : Memory cell 71 (hex 47) > Contents 120 1 2 … 98 99 135 116 … 128 133 78 87 49 74 : : A9 Memory cell 170 (hex AA) Memory > 47 48 Conceptually, the array looks Conceptually, something like this: something Index 0 Content s 80 AA 85 : FE Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 7 Page Addres s Content s 00 01 : Space for element (0,0) > B2 5E (0,1) > B3 59 (0,2) > B4 64 (0,3) > B5 57 (0,4) > B6 5C (1,0) > B7 44 (1,1) > B8 5A (1,2) > B9 54 (1,3) > BA 4E 4 (1,4) > BB 56 A multidimensional array is an multidimensional indexed table of values of the same type, using more than one dimension. dExample: imension. int GradeTable[3][5]; Conceptually, the array looks Conceptually, something like this: something COLUMN # 0 2 0 94 89 100 87 92 (2,0) > BC 4D 1 68 90 84 78 86 (2,1) > BD 5F 2 77 ROW # 1 3 95 97 100 88 (2,2) > BE 61 (2,3) > BF 64 (2,4) > C0 58 However, in the computer’s RAM, space for However, 15 integers has been allocated something like this: like : FF Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 8 Page Rather than reserving a contiguous Rather block of memory to store a list, the linked list dynamically allocates memory as needed for list elements. memory However, in the However, computer’s RAM, space for 4 integers has been allocated something like this: something Example: struct node; typedef node *nodePtr; struct node { int value; int nodePtr next; nodePtr }; 3rd item is at address B0 00 : 64 17 B0 : 4E FF signifies the end of FF List List Conceptually, the linked list Conceptually, looks something like this: looks 100 Content s 16 nodePtr List; 97 Addres s 88 5E 4F FF : 94 List is located at 9A 9A 61 2nd item is at address 16 9B 16 : B0 4th item is at address 4E 58 B1 4E Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 9 Page Relative Advantages of Arrays & Linked Relative Lists Lists Arrays Linked Lists Require contiguous memory Dynamically locate memory Requires specific size Has flexible size Potentially wastes memory Only uses allocated space Potentially runs out of Potentially memory memory Insertion requires Insertion rearranging rearranging Deletion requires Deletion rearranging rearranging Indexing facilitates searching Expands memory as needed Binary search possible if Binary sorted sorted Straightforward to program Memory easily cleared after Memory use use Insertion requires slight Insertion relink relink Deletion requires slight relink One-by-one searching One-by-one required required Sequential search only Tougher to conceptualize Complicated garbage Complicated collection collection Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 10 Page 10 Comparison: Retrieving a List from a File Using an array void GetList(int List[50], void int &ListSize) int &ListSize) { ifstream file; ifstream char fileName[50]; char int val; int Using a linked list void GetList(nodePtr &List) { ifstream file; ifstream char fileName[50]; char int val; int nodePtr ptr; nodePtr cout << "Enter the name " cout << "of the file: "; << cin >> fileName; cin file.open(fileName); file.open(fileName); assert(!file.fail()); assert(!file.fail()); cout << "Enter the name " cout << “of the file: "; << cin >> fileName; cin file.open(fileName); file.open(fileName); assert(!file.fail()); assert(!file.fail()); ListSize = 0; ListSize file >> val; file while while ((!file.eof()) && && (ListSize < 50)) 50)) (ListSize { List[ListSize] = val; List[ListSize] ListSize++; ListSize++; file >> val; file } file.close(); file.close(); List = NULL; List file >> val; file while (!file.eof()) while { ptr = new node; ptr ptr->value = val; ptr->value ptr->next = List; ptr->next List = ptr; List file >> val; file } file.close(); file.close(); } Extra concern: Exceeding array’s Extra size size } Extra concern: Allocating new Extra Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 11 Page 11 Comparison: Sequential Search Using an array int Search(int int int int int { int count; int bool found = bool List[50], ListSize, soughtVal) Using a linked list int Search(nodePtr List, int soughtVal) int { nodePtr currPtr; nodePtr bool found = false; bool false; currPtr = List; currPtr count = 0; while ((!found) && count while while ((!found) && (currPtr != NULL)) while (currPtr (count < 50)) { (count { if (currPtr->value == if if (List[count] == soughtVal) if soughtVal) soughtVal) found = true; soughtVal) found Note ound = true; the code is almost identical, but the array again that found else f else else currPtr->next; else currPtr version is limited to lists of a certain currPtrIf=the list is too long, size. count++; } count++; the}array can’t hold it all; if it’s toofshort, several memory slots if (found) i if (found) return currPtr->value; if return are wasted. return List[count]; else return else else return -1 else return Chapter 9 return -1; } Chapter return Abstract Data Abstract Types and } Algorithms Algorithms Page 12 Page 12 Sorting Algorithms Somewhat more complicated than searching an Somewhat alphabetized list is the problem of alphabetizing such a list to begin with. to Numerous sorting algorithms have been developed, each Numerous with its own advantages and disadvantages with respect to: with • Speed with which it sorts a completely Speed • random list which it sorts a nearly sorted list Speed with random • Amount of memory required to implement it • Ease with which it can be coded Examination of three such algorithms follows, with each Examination algorithm applied to the following list of 26 three-letter names: names: Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 13 Page 13 Selection Sort 1. 2. 3. Moe Let k equal the size of your list Let Let i equal the index of the first element of your list Let Swap the smallest element in the last k elements with the ith Swap element element 4. Decrease k by one Decrease 5. Increase i by one Increase 6. If k is still Ann Uma than one, repeat, starting at step #3 larger If Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Edy Tia Ann Edy Zeb Ort Bob Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Zeb Bob Wes Ann Bob Zeb Ort Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Ort Cub Ida Ann Bob Cub Ort Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Dan Lex Pez Hal Tia Edy Dan Lex Ann Bob Cub Dan Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal Tia Wes Ann Bob Cub Dan Edy Wes Moe Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal Tia Moe Fly Vin Ann Bob Cub Dan Edy Fly Moe Uma Quo Kit Wes Vin Xon Gus Joe Nan Sue Zeb Ida Yul Ren Ort Lex Pez Hal Tia Ann Bob Cub Dan Edy Fly Gus Hal Ida Joe Kit Lex Moe Nan Ort Pez Quo Ren Sue Tia Uma Vin Wes Xon Yul Zeb Verdict: Easy to program, little memory waste, very Verdict: inefficient inefficient Chapter 9 Chapter Abstract Abstract Data Types and Algorithms Algorithms Page 14 Page 14 Bubble Sort 1. 2. 3. 4. 5. 6. Let k equal the size of your list Let Let i equal the index of the first element of your list Let Starting with the ith element of the list and moving down to the kth element, Starting swap every consecutive pair of elements that is in the wrong order swap Decrease k by one Decrease Increase i by one Increase If k is still larger than one, repeat, starting at step #3 If Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Zeb Edy Moe Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Moe Ort Edy Edy Moe Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Bob Wes Edy Moe Ort Zeb Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Edy Moe Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Zeb Edy Moe Bob Ort Ann Uma Quo Kit Fly Vin Wes Gus Joe Nan Sue Cub Ida Xon Ren Dan Lex Pez Hal Tia Yul Zeb Ann Bob Cub Dan Edy Fly Gus Hal Ida Joe Kit Lex Moe Nan Ort Pez Quo Ren Sue Tia Uma Vin Wes Xon Yul Zeb Verdict: Tougher to program, little memory waste, inefficient in Verdict: general (but could easily be modified to terminate early if a swapgeneral less pass occurs) Chapter 9 Abstract Abstract Data Types and Algorithms Algorithms Page 15 Page 15 Quick Sort 1. Let leftIndex be the index of the leftmost element of an unsorted portion of Let leftIndex the list and rightIndex be the index of the rightmost element of that portion of rightIndex the list the 2. Let pivot equal the value currently at index p of the list Let pivot 3. Moving in from the rightIndex element of the list, keep moving until a value Moving rightIndex less than pivot is found; set rightIndex to the index of that value and insert it pivot rightIndex at position leftIndex leftIndex 4. Moving in from the leftIndex element of the list, keep moving until a value Moving leftIndex greater than pivot is found; set leftIndex to the index of that value and insert pivot leftIndex it at position rightIndex rightIndex pivot Moe 5. If leftIndex doesn’t equal rightIndex, return to step #3; otherwise, insert pivot If :leftIndex rightIndex return pivot Hal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Moe Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Hal Tia Lex Dan Ida Cub Joe Gus Moe Xus Jin Vin Xon Gon Vin Nan Voe Quo Uma Cub Ida Yul Uma Wes Lex Dan Ort Pez Hal Tia Ort Zeb at index leftIndex and return to step #1, starting over with another unsorted leftIndex portion portion pivot Hal of the list : Gus Edy Fly Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Bob Cub Ann Hal Joe Kit Ida Lex pivot Xon : Gus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Xon Zeb Tia Tia Vin Nan Quo Pez Wes Pez Yul Ann Bob Cub Dan Edy Fly Gus Hal Ida Joe Kit Lex Moe Nan Ort Pez Quo Ren Sue Tia Uma Vin Wes Xon Yul Zeb Verdict: Much tougher to program, little memory waste, efficient in Verdict: general (but very inefficient if the list is already almost sorted) general Chapter 9 Chapter Abstract Abstract Data Types and Algorithms Algorithms Page 16 Page 16 A stack is a data structure that stack manages a list of similar items in such a way that all insertions and deletions take place at one designated end of the list. designated In effect, one end of the list is considered the “top” of the stack, In inserting into the list is considered “pushing” an item onto the top of the stack, and deleting from the list is considered “popping” off the top of the stack. top Example: 3 Initial Initial Stack Stack 5 3 8 5 3 5 3 3 1 3 After After “Push 3” “Push After After “Push 5” “Push After After “Push 8” “Push After After “Pop” “Pop” After After “Pop” “Pop” After After “Push 1” “Push Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 17 Page 17 Comparison: Stack Implementations Using an array void Push(int List[50], int &Top, int int item) int { if (Top < 49) if { Top++; Top++; List[Top] = item; List[Top] } } int Pop(int List[50], int &Top) int { int val = -1; int if (Top >= 0) if { val = List[Top]; val Top--; Top--; } return val; return } Using a linked list void Push(nodePtr &List, int item) int { nodePtr ptr = new node; nodePtr ptr->value = item; ptr->value ptr->next = List; ptr->next List = ptr; List } int Pop(nodePtr &List) { int val = -1; int if (nodePtr != NULL) if { val = nodePtr->value; val List = List->next; List } return val; return } Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 18 Page 18 Keeping track of function Keeping calls in a third-generation programming language. programming Example Stack Application Main Program x = 0; y = -2; A(); z = 6; cout << x << y << z << endl; << Subprogram Subprogram A() A i = 10; () j = 46; k = 31; B(); j = 50; cout << i << j << k << endl; << Subprogram Subprogram B() B() r = 400; s = 542; C(); r = 710; s = 365; r = 927; cout << r << s << t << endl; << B: line #3 r:400 s:542 t:? A: line #4 i:10 j:46 k:31 Main: line #3 x:0 y:-2 z:? When Main When reaches the A(); step step A: line #4 i:10 j:46 k:31 Main: line #3 x:0 y:-2 z:? Main: line #3 x:0 y:-2 z:? When A reaches When the B(); step the When B reaches When the C(); step the Subprogram Subprogram C() C u = 15; () v = 57; w = 34; cout << u << v << w << endl; << When C finishes, the When stack is popped and B resumes. resumes. When B finishes, the When stack is popped and A resumes. resumes. When A finishes, the When stack is popped and Chapter 9 Chapter Main resumes and Abstract Data Abstract Types and finishes. finishes. Algorithms Algorithms Page 19 Page 19 A queue is a data structure that manages a queue list of similar items in such a way that all insertions take place at one end of the list, while all deletions take place at the other end. end. In effect, one end of the list is considered the “rear” of the queue, In where new items enter; and the other end is considered the “front” of the queue, where old items are removed. the Example: F Initial Queue: After Insert 2: 7 After Remove: F After Insert 4: 4 4 R 4 2 F R 7 7 F F/R After Insert 7: R After Insert 5: 4 2 R 2 5 Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 20 Page 20 Comparison: Queue Implementations Using an array Using a linked list void Insert(int List[50], int &Front, int &Rear, int item) { if (Front != (Rear+1)%50) { Rear = (Rear+1)%50; List[Rear] = item; if (Front == -1) Front = Rear; } } int Remove(int List[50], int &Front, int &Rear) { int val = -1; if (Front > -1) { val = List[Front]; if (Front == Rear) Front = Rear = -1; else Front = (Front+1)%50; } return val; } void Insert(nodePtr &ListFront, nodePtr &ListRear, int item) { nodePtr ptr = new node; ptr->value = item; ptr->next = NULL; if (ListFront == NULL) ListFront = ptr; else ListRear->next = ptr; ListRear = ptr; } int Remove(nodePtr &ListFront, nodePtr &ListRear) { int val = -1; if (ListFront != NULL) { val = ListFront->value; ListFront = ListFront->next; } if (ListFront == NULL) ListRear = NULL; return val; } Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 21 Page 21 Keeping track of batch Keeping jobs as they arrive to be processed by a computer. processed Example Queue Application Job A arrives Job CPU CPU and starts processing processing: processing: Job Queue: Job A Job Job B Job arrives: arrives: Jobs C & D Jobs arrive: arrive: Job A Job completes; Job B starts processing: processing: CPU CPU processing Job A Job Job Queue: B CPU CPU processing Job A Job Job Queue: B C CPU CPU processing Job B Job Job Queue: C D D Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 22 Page 22 Example Example Implementation: Implementation: A binary tree is a hierarchical data binary structure that manages a collection of similar items in such a way that one item is designated as the “root” of the tree, and every other item is either the left or right “offspring” of some previously positioned item. positioned struct node; typedef node *nodePtr; struct node { int value; int nodePtr left; nodePtr Example: Binary Insertion Tree nodePtr right; nodePtr •Each left offspring of a node has a value Each }; nodePtr Tree; less than the node’s value less •Each right offspring of a node has a Each value greater than or equal to the node’s value value Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 23 Page 23 Recursive Insertion into a Binary Insertion Recursive void Bin_Insert(nodePtr &Tree, int item) Tree Tree { if (Tree == NULL) if { nodePtr ptr = new node; nodePtr ptr->value = item; ptr->value ptr->left = NULL; ptr->left ptr->right = NULL; ptr->right } else if (item < Tree->value) else Bin_Insert(Tree->left, item); Bin_Insert(Tree->left, else else Bin_Insert(Tree->right, item); Bin_Insert(Tree->right, } Example: Where will a new node Where containing the integer 11 be inserted? 11 Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 24 Page 24 Recursive Traversal of a Binary Insertion Tree void Inorder(nodePtr Tree) { if (Tree != NULL) if { Inorder(Tree->left); Inorder(Tree->left); cout << Tree->value << endl; cout Inorder(Tree->right); Inorder(Tree->right); } } Example: Apply Inorder to this Apply binary insertion tree: binary Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 25 Page 25 What Does This Function Do To A Binary What Tree? Tree? int Sumac(nodePtr Tree) { int leftbranch, rightbranch; int if (Tree == NULL) if return 0; return else else { leftbranch = Sumac(Tree->left); leftbranch rightbranch = Sumac(Tree->right); rightbranch return leftbranch + rightbranch + Tree->value; return } } 125 61 34 22 0 0 51 0 31 9 15 00 0 0 0 0 Chapter 9 Chapter Abstract Data Abstract Types and Algorithms Algorithms Page 26 Page 26 ...
View Full Document

This note was uploaded on 08/26/2009 for the course CS 111 taught by Professor Klein,s during the Fall '08 term at Southern Illinois University Edwardsville.

Ask a homework question - tutors are online