Presentation is loading. Please wait.

Presentation is loading. Please wait.

Similar presentations


Presentation on theme: ""— Presentation transcript:

56 Chapter 6: Problem Solving and Algorithm Design
In general, how are problems solved on a computer? Analysis & Specification Understand the problem Specify what the program needs to do Algorithm Development Formulate sequence of steps for solving problem Test that the steps work for certain key cases Implementation Translate the algorithm into a programming language Test whether the program produces correct results Maintenance Deliver the program and have real users use it Debug and upgrade the program as needed Chapter 6 Problem Solving and Algorithm Design Page 56

57 Problem Solving and Algorithm Design
Algorithms An algorithm is an ordered set of unambiguous, executable steps that ultimately terminate if followed. Ambiguous: Not executable: Lather Chapter 6 Problem Solving and Algorithm Design Page 57 No termination: Rinse Repeat

58 Problem Solving and Algorithm Design
Computer Algorithms In computer programming, an algorithm is the sequence of steps (i.e., the “recipe”) for accomplishing a task. Every step in an algorithm has two basic components: Semantics: The meaning of the step Syntax: The format of the step Semantics Get a value from the user Double that value Return the result to the user Syntax Program DoubleIt; var x, y integer; begin write(“Input your number: ”); read(x); y = 2*x; writeln(“The doubled number is ”, y); end. Chapter 6 Problem Solving and Algorithm Design Page 58

59 Pseudocode Pseudocode is an informal notation for expressing an algorithm. Procedure Sat1231A Set year to 2001 Set month to January Set day to first Saturday in January 2001 While (year < 2021) Do { Increment day by 7 If date is New Year’s Eve Then display year as having a Saturday New Year’s Eve If day > (number of days in month) Then Adjust day by subtracting the number of days in month If month is December Increment year by 1 } Else Increment month by one Example: Which years in have New Year’s Eve on Saturday? Chapter 6 Problem Solving and Algorithm Design Page 59

60 Problem Solving and Algorithm Design
Algorithm Alternatives It’s possible to devise many algorithms to solve the same problem. Procedure Sat1231B Set day_of_week to 12/31/2000 Set year to 2001 While (year < 2021) Do { If year is a leap year Then increment day_of_week by 2 Else increment day_of_week by 1 If day_of_week is Saturday Then display year as having a Saturday New Year’s Eve Increment year by 1 } Alternative pseudocode to determine which years in have New Year’s Eve on Saturday. Both algorithms work, but which is better? Which is easier to code? Which runs more efficiently? Chapter 6 Problem Solving and Algorithm Design Page 60

61 Networking Capability Artificial Intelligence
Program Modularity The software development process usually involves a team of developers, so the software is often designed as a hierarchical system of modules, which can be viewed as easily modified interdependent entities. Video Game Networking Capability Data Security Server Access Customer Billing Game Play Animation Character Animation Special Effects Backgrounds Artificial Intelligence Sound Music Voice Sound Effects Chapter 6 Problem Solving and Algorithm Design Page 61

62 Problem Solving and Algorithm Design
Advantages of Modular Programming Modifiability It’s easier to alter or upgrade the program if changes can be segregated to particular modules Debuggability It’s easier to diagnose and pinpoint problems with the program if it’s split into logically distinct modules Reusability Generic modules can be developed and then reused in other programs, eliminating the need to “reinvent the wheel” Readability It’s easier to read someone else’s program or refresh you memory about your own program if it’s broken into self-contained units Chapter 6 Problem Solving and Algorithm Design Page 62

63 Computer Graphics Modularity Example
Initially, set the program up to calculate the scene with simple lighting. Replace the simple lighting with more sophisticated reflective surfaces. Add a module to smooth out the silhouettes of objects. main generate polygons torus cube teapot sphere cone draw shade polygon pixels main generate polygons torus cube teapot sphere cone draw blend compute reflect pixels main generate polygons torus cube teapot sphere cone draw blend compute reflect pixels curved surfaces Chapter 6 Problem Solving and Algorithm Design Page 63

64 Top-Down Design One common approach for designing programs is the top-down methodology. Design a high-level solution to the programming problem. Consider each complicated subproblem as a separate programming problem. Return to step #1 with each subproblem. Process Payroll Get Input Data Retrieve Timecard Data Retrieve Salary Information Retrieve Dependent Records Retrieve Retirement Plans Retrieve Tax Rates Perform Calculations Compute Gross Pay Compute Deductions Produce Output Generate Paychecks Update YTD Records This approach lends itself to modularity. However, it may impose an artificial hierarchy on the tasks being performed. Chapter 6 Problem Solving and Algorithm Design Page 64

65 Bottom-Up Design A newer approach for designing programs is the bottom-up methodology. Separate each major task in the overall problem into an individual programming problem. Develop cooperative programming solutions to the separate problems. Video Game Engine Physics Engine Fluid Dynamics Engine Particle Systems Engine Collision Detection Engine Math Engine Rotational Calculation Engine Fractal Engine Artificial Intelligence Engine Intelligent Agent Engine Behavior Prediction Engine This approach produces reusable modules. However, those modules may prove difficult to cobble together to solve bigger problems. Chapter 6 Problem Solving and Algorithm Design Page 65

66 Chapter 7: Low-Level Programming Languages
In order to execute instructions on a CPU, those instructions must be in the particular binary format that was designed for that CPU. The set of instructions available for a particular CPU is known as its machine language. Sample Machine Instruction Format Op-Code Field (specifies the operation to be performed) Operand Field (gives further details pertinent to the operation) Chapter 7 Low-Level Programming Languages Page 66

67 Low-Level Programming Languages
Simplified Machine Language Op-Code Operand Description 1 RXY LOAD register R with the bit pattern found at main memory address XY 2 LOAD register R with the bit pattern XY 3 STORE the bit pattern in register R at main memory address XY 4 0RS MOVE the bit pattern in register R to register S 5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R 6 ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R 7 OR the bit patterns in registers S and T and put the result in register R 8 AND the bit patterns in registers S and T and put the result in register R 9 XOR the bit patterns in registers S and T and put the result in register R A R0X ROTATE the bit pattern in register R a total of X bits to the right B JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence C 000 HALT execution Note that every instruction is sixteen bits (four hexadecimal digits) in length. Chapter 7 Low-Level Programming Languages Page 67

68 Low-Level Programming Languages
Sample Program 205C Load register 0 with the integer 92 (hexadecimal 5C) 300E Store the contents of register 0 at main memory address 0E 205A Load register 0 with the integer 90 (hexadecimal 5A) 300F Store the contents of register 0 at main memory address 0F 110E Load register 1 with the bit pattern at main memory address 0E 120F Load register 2 with the bit pattern at main memory address 0F 5012 Add the contents of registers 1 & 2 and put the sum in register 0 300D Store the contents of register 0 at memory address 0D C000 Halt execution Op-Code Operand Description 1 RXY LOAD register R with the bit pattern found at main memory address XY 2 LOAD register R with the bit pattern XY 3 STORE the bit pattern in register R at main memory address XY 4 0RS MOVE the bit pattern in register R to register S 5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R 6 ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R 7 OR the bit patterns in registers S and T and put the result in register R 8 AND the bit patterns in registers S and T and put the result in register R 9 XOR the bit patterns in registers S and T and put the result in register R A R0X ROTATE the bit pattern in register R a total of X bits to the right B JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence C 000 HALT execution In an advanced language, like C++, this program would be: void main() { int X, Y, Z; X = 92; Y = 90; Z = X + Y; } Chapter 7 Low-Level Programming Languages Page 68

69 Low-Level Programming Languages
Another Sample Program How would we code this pseudocode with our machine language? Procedure negative (x) If x < 0 Then return 1 Else return 0 We’ll assume that the value of x has already been stored in main memory at address 5A, that the returned value (0 or 1) will be placed at address 5B, and that the program itself will be stored starting at address D0. Op-Code Operand Description 1 RXY LOAD register R with the bit pattern found at main memory address XY 2 LOAD register R with the bit pattern XY 3 STORE the bit pattern in register R at main memory address XY 4 0RS MOVE the bit pattern in register R to register S 5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R 6 ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R 7 OR the bit patterns in registers S and T and put the result in register R 8 AND the bit patterns in registers S and T and put the result in register R 9 XOR the bit patterns in registers S and T and put the result in register R A R0X ROTATE the bit pattern in register R a total of X bits to the right B JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence C 000 HALT execution Chapter 7 Low-Level Programming Languages Page 69

70 Meaning of Instruction Low-Level Programming Languages
Let’s take advantage of the fact that if an 8-bit two’s-complement number is ANDed with , the result is if the number is positive, and if the number is negative. Address Contents Meaning of Instruction D0 D1 11 5A LOAD register 1 with the value of x (stored at address 5A) D2 D3 20 80 LOAD register 0 with the eight bit sequence D4 D5 82 01 AND the contents of registers 0 and 1, putting the result in register 2 D6 D7 B2 DC If the result is (i.e., if x is negative), jump to the instruction at RAM address DC D8 D9 23 00 Otherwise, load register 3 with the number 0 DA DB B0 DE Jump to the instruction at main memory location DE DD Load register 3 with the number 1 DF 33 5B Store the contents of register 3 in main memory at address 5B E0 E1 C0 Halt execution Op-Code Operand Description 1 RXY LOAD register R with the bit pattern found at main memory address XY 2 LOAD register R with the bit pattern XY 3 STORE the bit pattern in register R at main memory address XY 4 0RS MOVE the bit pattern in register R to register S 5 RST ADD the bit patterns in registers S and T (using two’s complement) and put the sum in register R 6 ADD the bit patterns in registers S and T (as floating-point numbers) and put the sum in register R 7 OR the bit patterns in registers S and T and put the result in register R 8 AND the bit patterns in registers S and T and put the result in register R 9 XOR the bit patterns in registers S and T and put the result in register R A R0X ROTATE the bit pattern in register R a total of X bits to the right B JUMP to the instruction at main memory address XY if the bit pattern in register R is the same as the bit pattern in register 0; otherwise, continue with the normal execution sequence C 000 HALT execution Procedure negative (x) If x < 0 Then return 1 Else return 0 Chapter 7 Low-Level Programming Languages Page 70

71 Assembly Language Example:
To make programming easier to handle, special languages (unique to the kinds of computers running them) have been developed. Programs written in such an assembly language are executed by first passing through a special program (called an assembler) that translates the assembly language code into machine language. Example: LOADVAR R1,X LOADHEX R0,80 AND R2,R0,R1 JUMPEQ R0,R2,NEGATIVE LOADHEX R3,00 JUMPEQ R0,R0,STOREIT NEGATIVE LOADHEX R3,01 STOREIT STORE R3, RESULT HALT Machine Language Feature Corresponding Assembly Language Feature Hexadecimal Op-Codes Mnemonic Operators (“LOADVAR”, “JUMPEQ”, etc.) Data In Specific Main Memory Locations User-Defined Variable Names (“X”, “RESULT”) Instruction Addresses In Main Memory User-Defined Instruction Labels (“NEGATIVE”, “STOREIT”) Chapter 7 Low-Level Programming Languages Page 71

72 Assembly Language Problems
While assembly languages are easier to use than machine languages, they still share two big problems with machine languages. 1. Assembly languages are still machine-dependent. A program written in one machine’s assembly language cannot be executed on a computer with a different instruction set and register configuration. 2. Assembly language programming is still too nitpicky. Programmers are forced to concentrate on the tiny details necessary to choreograph the computer’s activity, instead of focusing on the overall solution of the problem being tackled. Chapter 7 Low-Level Programming Languages Page 72

73 High-Level Programming Languages
Chapter 8: High-Level Programming Languages Third-generation languages (e.g., BASIC, FORTRAN, COBOL, C) were developed as a solution to the assembly language problems. Third-generation languages are structured to avoid considering machine operations at all, instead concentrating on relatively straightforward instructions on how the data is being manipulated. Each type of computer that executes programs in a TGL has a special program (called a compiler) that translates the TGL code into the computer’s machine language. Example: int negative (int x) { if (x < 0) return 1; else return 0; } Consequently, a TGL program written on one machine can be run on any other computer, as long as the computer has a compiler for that TGL! Chapter 8 High-Level Programming Languages Page 73

74 High-Level Programming Languages
Compilation Source Program (in TGL) Object Program (in Machine Language) Lexical Analysis Parsing Code Generation Lexical Analysis The compiler takes the TGL program (called the source program) and determines which strings of characters form separate items (e.g., “if (count > 100)” is split into “if”, “(”, “count”, “>”, “100”, and “)”), and all comments and white space (blanks, line feeds, etc.) are deleted. Parsing The compiler then analyzes the grammatical syntax of the program (e.g., “if”, “(”, “count”, “>”, “100”, “)” is determined to make sense, but a syntax error would be noticed in “if”, “count”, “>”, “100”, “)”.) Code Generation Once the program has been satisfactorily parsed, the compiler generates an equivalent program in machine language (called the object program). Chapter 8 High-Level Programming Languages Page 74

75 High-Level Programming Languages
Linking and Loading Since the individual portions of the TGL program are compiled as separate units (e.g., your program, a math library, a graphics library, etc.), the resulting machine code cannot be executed until all of the units are connected together as a single machine language program. Source Program Object Program Load Module Executable Program Compile Link Load Linking A TGL programmer usually relies on pre-compiled libraries of code (math functions, graphics routines, I/O operations, etc.) that are connected to the programmer’s code prior to execution by a linker program. Loading Finally, a special loader program places the resulting machine code in main memory, tying up all loose ends (e.g., setting the instruction addresses for JUMP instructions) so the code is ready for execution. Chapter 8 High-Level Programming Languages Page 75

76 Standard Source Program Organization
Source programs in most third-generation languages generally follow a standard pattern. void main() { const int maxCount = 10; int count; int value; float sum = 0.0; cout << “Input values” << endl; count = 0; while (count < maxCount) cin >> value; sum += value; count++; } cout << “Mean value: ” << sum/count << endl; void main() { const int maxCount = 10; int count; int value; float sum = 0.0; cout << “Input values” << endl; count = 0; while (count < maxCount) cin >> value; sum += value; count++; } cout << “Mean value: ” << sum/count << endl; void main() { const int maxCount = 10; int count; int value; float sum = 0.0; cout << “Input values” << endl; count = 0; while (count < maxCount) cin >> value; sum += value; count++; } cout << “Mean value: ” << sum/count << endl; Declarative Statements Constant and variable values representing terms that will be manipulated as the program is executed. Imperative Statements The procedural specification of the algorithm itself. Chapter 8 High-Level Programming Languages Page 76

77 High-Level Programming Languages
Data Types Data types are used to specify how the bit patterns used to represent data should be interpreted by the program. Scalar: Single-valued data types (e.g., integer, floating-point, character, boolean) int count; float price; bool flag; Structured: Multiple-valued data types Built-In: Arrays, character strings float CaffeineOuncesPerDay[7]; char chosenCola[] = “Pepsi”; User-Defined: Specially constructed struct Student { char name[30]; int examScore[5]; int quizScore[25]; int paperScore[2]; char letterGrade; }; Student FALL111[25]; Chapter 8 High-Level Programming Languages Page 77

78 High-Level Programming Languages
Imperative Statements - Part One Assignment & I/O Assignment statements are used to assign a value to a variable. x = 127; c count E m x 186000 78 5 290 c count E m x 186000 78 5 127 c count E m x 186000 79 930000 5 127 c count E m x 186000 79 5 127 c count E m x 186000 79 930000 5 127 count = count + 1; E = m * c * c; Input/output statements are used to retrieve external values (input) and to file away or print information (output). Enter user’s name: MOE cout << “Enter user’s name: ”; cin >> username; dataFile >> nextDataValue; if (nextDataValue > 0) positiveFile << nextDataValue; dataFile positiveFile 25 nextDataValue 25 nextDataValue 94 nextDataValue 25 Chapter 8 High-Level Programming Languages Page 78

79 High-Level Programming Languages
Imperative Statements - Part Two Control Statements Conditional statements are used to enable alternative steps based on a condition. if (total == 0) cout << “Possible Drop”; else cout << “Total: ” << total; switch (AreaCode) { case 701: cout << “ND”; break; case 218: case 507: case 612: cout << “MN”; break; } Iterative statements are used to loop through a sequence of instructions. while (flag == false) { cin >> newValue; if (newValue > 0) flag = true; } total = 0; for (i = 0; i <= 24; i++) { quizFile >> score[i]; total += score[i]; } Chapter 8 High-Level Programming Languages Page 79

80 High-Level Programming Languages
Imperative Statements - Part Three Procedures & Functions Procedures and functions are used to conveniently write programs in a modular fashion. typedef int intList[100]; void getList(intList list) { int count; for (count = 0; count < 100; count++) cin >> list[count]; } int maximum(intList list) int maxSoFar; maxSoFar = list[0]; for (count = 1; count < 100; count++) if (list[count] > maxSoFar) maxSoFar = list[count]; return maxSoFar; void main() { intList IQlist; intList SATlist; int maxIQ; int bestSAT; getList(IQlist); maxIQ = maximum(IQlist); getList(SATlist); bestSAT = maximum(SATlist); cout << “The highest IQ is ” << maxIQ << “ and the ” << “best SAT score is ” << bestSAT; } Chapter 8 High-Level Programming Languages Page 80

81 Example: What Does This Program Do?
typedef int intList[4]; void getList(intList list) { int count; for (count = 0; count < 4; count++) cin >> list[count]; } int drew(intList list, int item) int bestSoFar, bestIndex, index; bestIndex = -1; bestSoFar = 0; for (index = 0; index < 4; index++) if ((list[index] > bestSoFar) && (list[index] <= item)) bestIndex = index; bestSoFar = list[index]; return bestIndex; void main() { intList estimate; int bestGuesser; int price; cin >> price; getList(estimate); bestGuesser = drew(estimate, price); if (bestGuesser == -1) cout << “NO WINNER”; else cout << bestGuesser << “ WINS! ”; if (estimate[bestGuesser] == price) cout << “WITH A BONUS!!!”; } What would be the output of this program for the following input file? Chapter 8 High-Level Programming Languages Page 81

82 High-Level Programming Languages
Object-Oriented Programming Early third-generation programming languages used a “procedure-oriented” approach, in which the way something was done was the center of attention for the programmer. More recently, with the advent of graphical user interfaces and massive databases, the focus has shifted to an “object-oriented” approach, emphasizing what is being manipulated instead of how. Chapter 8 High-Level Programming Languages Page 82

83 High-Level Programming Languages
The Three Principles of OOP Encapsulation “Hide” information from objects that don’t need it. Is the search being performed sequential or binary? Is the data in an array or separate variables? Is the input coming from the user or from a file? The code will be more robust if it’s not unnecessarily dependent on information that it can perform without! Inheritance Don’t “reinvent the wheel” when creating new data types. A GUI Window is rectangular with a title bar. A Document Window also has a menu bar, and max & min buttons. Why not let the Document Window “inherit” as much behavior as possible from the GUI Window (e.g., how to draw it, how to place text in its title bar)? Polymorphism Some objects are “similar”, without being the same. A Triangle object needs its own method for “Drawing”. A Circle object needs its own method for “Drawing”. With polymorphism, you can write code to invoke “Drawing” without having to spell out what type of “Drawing” is intended. Chapter 8 High-Level Programming Languages Page 83

84 Abstract Data Types and Algorithms
Chapter 9: Abstract Data Types and Algorithms Two keys to making computer software that works well: Organize data so it can be accessed and processed efficiently. Develop algorithms that take advantage of the strengths of the programming language and the hardware to accomplish what the program is attempting to do. Chapter 9 Abstract Data Types and Algorithms Page 84

85 Abstract Data Types and Algorithms
Iteration When an algorithm involves repetitive actions, iteration (i.e., looping) may be a practical approach. Pseudocode to implement the search for a specific name in an alphabetized phonebook: Procedure SeqSearch(phonebook, sought_name) Set test_name to first name in phonebook While (test_name is alphabetically before sought_name AND there are still more names in phonebook) Do Set test_name to the next name in phonebook If test_name is sought_name Then return the corresponding phone number Else return “Unlisted” message Notice that this algorithm always starts at the top of the phonebook list and checks each name against sought_name until it either locates it or (if it’s not in the phonebook) passes it. Chapter 9 Abstract Data Types and Algorithms Page 85

86 Abstract Data Types and Algorithms
Calling SeqSearch(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list below: Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver 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 Chapter 9 Abstract Data Types and Algorithms Page 86

87 Abstract Data Types and Algorithms
Recursion Another common approach in algorithms is to employ recursion (i.e., “divide and conquer”), which repeatedly reduces the size of a problem until it becomes manageable. Pseudocode to recursively take a base number to a specified power: Procedure Exponentiate(base, power) If base is 0 Then return 0 Else If power < 0 Then return Exponentiate(base, power+1)/base Else If power is 0 Then return 1 Else return base * Exponentiate(base, power-1) Notice that this algorithm returns 0 if the value of base is 0, 1 if the value of power is 0, base if the value of power is 1, 1/base if the value of power is -1, and so on. Chapter 9 Abstract Data Types and Algorithms Page 87

88 Abstract Data Types and Algorithms
A Recursive Search Algorithm Pseudocode to recursively implement the search for a specific name in an alphabetized phonebook: Procedure BinarySearch(phonebook, sought_name) Set test_name to the middle name in phonebook If test_name is sought_name Then return corresponding phone number Else If phonebook has only one remaining entry Then return “Unlisted” message If test_name is alphabetically before sought_name Then apply BinarySearch to the portion of phonebook after test_name Else apply BinarySearch to the portion of phonebook before test_name Notice that this algorithm starts at the middle of the phonebook list, and keeps splitting what’s left of the phonebook in half until it either locates sought_name or runs out of names to check. Chapter 9 Abstract Data Types and Algorithms Page 88

89 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Calling BinarySearch(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list below: Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver Name Number Black, Sirius Chang, Cho Dumbledore, Albus Dursley, Dudley Filch, Argus Fudge, Cornelius Granger, Hermione Hagrid, Rubeus Lockhart, Gilderoy Longbottom, Neville Malfoy, Draco McGonagall, Minerva Pettigrew, Peter Pomfrey, Poppy Snape, Severus Trelawney, Sybill Weasley, Ron Wood, Oliver 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 test_name is Gilderoy Lockhart, so iterate again Chapter 9 Abstract Data Types and Algorithms Page 89 Chapter 9 Abstract Data Types and Algorithms Page 89

90 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Data Structures When interrelated information is stored in a computer’s memory, it is usually convenient for the programmer (and for the computer’s memory management) to keep this data in a structured format. However, in the computer’s RAM, space for 100 integers has been allocated something like this: Data Structure #1: The Array Address Contents 00 01 : Memory cell 71 (hex 47) > 47 78 48 87 49 74 A9 80 Memory cell 170 (hex AA) > AA 85 FE FF An array is an indexed list of values of the same type. Example: int IQlist[100]; Conceptually, the array looks something like this: Index 1 2 98 99 Contents 120 135 116 128 133 Chapter 9 Abstract Data Types and Algorithms Page 90 Chapter 9 Abstract Data Types and Algorithms Page 90

91 Data Structure #2: The MultidimensionalArray
Address Contents 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 (1,4) > BB 56 (2,0) > BC 4D (2,1) > BD 5F (2,2) > BE 61 (2,3) > BF (2,4) > C0 58 FF A multidimensional array is an indexed table of values of the same type, using more than one dimension. Example: int GradeTable[3][5]; Conceptually, the array looks something like this: COLUMN # 1 2 3 4 ROW # 94 89 100 87 92 68 90 84 78 86 77 95 97 88 However, in the computer’s RAM, space for 15 integers has been allocated something like this: Chapter 9 Abstract Data Types and Algorithms Page 91 Chapter 9 Abstract Data Types and Algorithms Page 91

92 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Rather than reserving a contiguous block of memory to store a list, the linked list dynamically allocates memory as needed for list elements. Data Structure #3: The Linked List Example: struct node; typedef node *nodePtr; struct node { int value; nodePtr next; }; nodePtr List; However, in the computer’s RAM, space for 4 integers has been allocated something like this: Address Contents 00 : 16 64 3rd item is at address B0 17 B0 4E 5E FF signifies the end of List 4F FF List is located at 9A 9A 61 2nd item is at address 16 9B 58 4th item is at address 4E B1 Conceptually, the linked list looks something like this: 97 100 88 94 Chapter 9 Abstract Data Types and Algorithms Page 92 Chapter 9 Abstract Data Types and Algorithms Page 92

93 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Relative Advantages of Arrays & Linked 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 memory Expands memory as needed Insertion requires rearranging Insertion requires slight relink Deletion requires rearranging Deletion requires slight relink Indexing facilitates searching One-by-one searching required Binary search possible if sorted Sequential search only Straightforward to program Tougher to conceptualize Memory easily cleared after use Complicated garbage collection Chapter 9 Abstract Data Types and Algorithms Page 93 Chapter 9 Abstract Data Types and Algorithms Page 93

94 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Comparison: Retrieving a List from a File Using an array Using a linked list void GetList(int List[50], int &ListSize) { ifstream file; char fileName[50]; int val; cout << "Enter the name " << "of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail()); ListSize = 0; file >> val; while ((!file.eof()) && (ListSize < 50)) List[ListSize] = val; ListSize++; } file.close(); void GetList(int List[50], int &ListSize) { ifstream file; char fileName[50]; int val; cout << "Enter the name " << "of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail()); ListSize = 0; file >> val; while ((!file.eof()) && (ListSize < 50)) List[ListSize] = val; ListSize++; } file.close(); void GetList(nodePtr &List) { ifstream file; char fileName[50]; int val; nodePtr ptr; cout << "Enter the name " << “of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail()); List = NULL; file >> val; while (!file.eof()) ptr = new node; ptr->value = val; ptr->next = List; List = ptr; } file.close(); void GetList(nodePtr &List) { ifstream file; char fileName[50]; int val; nodePtr ptr; cout << "Enter the name " << “of the file: "; cin >> fileName; file.open(fileName); assert(!file.fail()); List = NULL; file >> val; while (!file.eof()) ptr = new node; ptr->value = val; ptr->next = List; List = ptr; } file.close(); Chapter 9 Abstract Data Types and Algorithms Page 94 Chapter 9 Abstract Data Types and Algorithms Page 94 Extra concern: Exceeding array’s size Extra concern: Allocating new memory

95 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Comparison: Sequential Search Using an array Using a linked list int Search(int List[50], int ListSize, int soughtVal) { int count; bool found = false; count = 0; while ((!found) && (count < 50)) if (List[count] == soughtVal) found = true; else count++; } if (found) return List[count]; return -1; int Search(nodePtr List, int soughtVal) { nodePtr currPtr; bool found = false; currPtr = List; while ((!found) && (currPtr != NULL)) if (currPtr->value == soughtVal) found = true; else currPtr = currPtr->next; } if (found) return currPtr->value; return -1 Note again that the code is almost identical, but the array version is limited to lists of a certain size. If the list is too long, the array can’t hold it all; if it’s too short, several memory slots are wasted. Chapter 9 Abstract Data Types and Algorithms Page 95 Chapter 9 Abstract Data Types and Algorithms Page 95

96 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Sorting Algorithms Somewhat more complicated than searching an alphabetized list is the problem of alphabetizing such a list to begin with. Numerous sorting algorithms have been developed, each with its own advantages and disadvantages with respect to: Speed with which it sorts a completely random list Speed with which it sorts a nearly sorted list Amount of memory required to implement it Ease with which it can be coded Examination of three such algorithms follows, with each algorithm applied to the following list of 26 three-letter 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 Abstract Data Types and Algorithms Page 96 Chapter 9 Abstract Data Types and Algorithms Page 96

97 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Selection Sort Let k equal the size of your list Let i equal the index of the first element of your list Swap the smallest element in the last k elements with the ith element Decrease k by one Increase i by one If k is still larger than one, repeat, starting at step #3 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 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 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 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 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 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 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 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 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 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 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 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 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 inefficient Chapter 9 Abstract Data Types and Algorithms Page 97 Chapter 9 Abstract Data Types and Algorithms Page 97

98 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Bubble Sort Let k equal the size of your list Let i equal the index of the first element of your list Starting with the ith element of the list and moving down to the kth element, swap every consecutive pair of elements that is in the wrong order Decrease k by one Increase i by one If k is still larger than one, repeat, starting at step #3 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 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 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 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 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 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 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 general (but could easily be modified to terminate early if a swap-less pass occurs) Chapter 9 Abstract Data Types and Algorithms Page 98 Chapter 9 Abstract Data Types and Algorithms Page 98

99 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Quick Sort Let leftIndex be the index of the leftmost element of an unsorted portion of the list and rightIndex be the index of the rightmost element of that portion of the list Let pivot equal the value currently at index p of the list Moving in from the rightIndex element of the list, keep moving until a value less than pivot is found; set rightIndex to the index of that value and insert it at position leftIndex Moving in from the leftIndex element of the list, keep moving until a value greater than pivot is found; set leftIndex to the index of that value and insert it at position rightIndex If leftIndex doesn’t equal rightIndex, return to step #3; otherwise, insert pivot at index leftIndex and return to step #1, starting over with another unsorted portion of the list pivot: Moe Hal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Quo Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Xon Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia 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 Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Gus Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Cub Joe Kit Fly Vin Xon Gus Joe Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia Hal Edy Lex Dan Bob Ida Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Uma Yul Ren Wes Ort Pez Zeb Tia Hal 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 Hal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb Tia Hal 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 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 Hal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Wes Ort Pez Zeb Tia 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 Hal Edy Zeb Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb Tia 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 Hal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb Tia Hal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb Tia Hal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb Tia Hal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb Tia Hal Edy Lex Ort Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Lex Pez Zeb Tia Hal Edy Lex Dan Bob Wes Ann Uma Quo Kit Fly Vin Xon Gus Joe Nan Sue Cub Ida Yul Ren Dan Ort Pez Zeb Tia pivot: Hal Gus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb Tia 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 pivot: Xon Gus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Tia Vin Nan Sue Quo Uma Pez Ren Wes Ort Xon Zeb Yul Gus Edy Fly Dan Bob Cub Ann Hal Joe Kit Ida Lex Moe Xon Vin Nan Sue Quo Uma Yul Ren Wes Ort Pez Zeb 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: Much tougher to program, little memory waste, efficient in general (but very inefficient if the list is already almost sorted) Chapter 9 Abstract Data Types and Algorithms Page 99 Chapter 9 Abstract Data Types and Algorithms Page 99

100 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Data Structure #4: The Stack A stack is a data structure that manages a list of similar items in such a way that all insertions and deletions take place at one designated end of the list. In effect, one end of the list is considered the “top” of the stack, 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. Example: Initial Stack 3 After “Push 3” 5 3 After “Push 5” 8 5 3 After “Push 8” 5 3 After “Pop” 3 After “Pop” 1 3 After “Push 1” Chapter 9 Abstract Data Types and Algorithms Page 100 Chapter 9 Abstract Data Types and Algorithms Page 100

101 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Comparison: Stack Implementations Using an array Using a linked list void Push(int List[50], int &Top, int item) { if (Top < 49) Top++; List[Top] = item; } int Pop(int List[50], int &Top) int val = -1; if (Top >= 0) val = List[Top]; Top--; return val; void Push(nodePtr &List, int item) { nodePtr ptr = new node; ptr->value = item; ptr->next = List; List = ptr; } int Pop(nodePtr &List) int val = -1; if (nodePtr != NULL) val = nodePtr->value; List = List->next; return val; Chapter 9 Abstract Data Types and Algorithms Page 101 Chapter 9 Abstract Data Types and Algorithms Page 101

102 Example Stack Application
Keeping track of function calls in a third-generation programming language. Main Program Subprogram A() Subprogram B() Subprogram C() x = 0; y = -2; A(); z = 6; cout << x << y << z << endl; x = 0; y = -2; A(); z = 6; cout << x << y << z << endl; i = 10; j = 46; k = 31; B(); j = 50; cout << i << j << k << endl; i = 10; j = 46; k = 31; B(); j = 50; cout << i << j << k << endl; r = 400; s = 542; C(); r = 710; s = 365; r = 927; cout << r << s << t << endl; r = 400; s = 542; C(); r = 710; s = 365; r = 927; cout << r << s << t << endl; u = 15; v = 57; w = 34; cout << u << v << w << endl; When C finishes, the stack is popped and B resumes. Main: line #3 x:0 y:-2 z:? When Main reaches the A(); step A: line #4 i:10 j:46 k:31 Main: line #3 x:0 y:-2 z:? When A reaches the B(); step 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 B reaches the C(); step When B finishes, the stack is popped and A resumes. When A finishes, the stack is popped and Main resumes and finishes. Chapter 9 Abstract Data Types and Algorithms Page 102 Chapter 9 Abstract Data Types and Algorithms Page 102

103 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Data Structure #5: The Queue A queue is a data structure that manages a 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. In effect, one end of the list is considered the “rear” of the queue, where new items enter; and the other end is considered the “front” of the queue, where old items are removed. Example: Initial Queue: F R After Insert 2: 7 4 2 F/R After Insert 7: 7 F R After Remove: 4 2 F R After Insert 4: 7 4 F R After Insert 5: 4 2 5 Chapter 9 Abstract Data Types and Algorithms Page 103 Chapter 9 Abstract Data Types and Algorithms Page 103

104 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
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; ListRear = NULL; return val; Chapter 9 Abstract Data Types and Algorithms Page 104 Chapter 9 Abstract Data Types and Algorithms Page 104

105 Example Queue Application
Keeping track of batch jobs as they arrive to be processed by a computer. CPU processing Job A Job A arrives and starts processing: Job Queue: Job B arrives: CPU processing Job A Job Queue: B Jobs C & D arrive: CPU processing Job A Job Queue: B C D Job A completes; Job B starts processing: CPU processing Job B Job Queue: C D Chapter 9 Abstract Data Types and Algorithms Page 105 Chapter 9 Abstract Data Types and Algorithms Page 105

106 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
Data Structure #6: The Binary Tree A binary tree is a hierarchical data 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. Example Implementation: struct node; typedef node *nodePtr; struct node { int value; nodePtr left; nodePtr right; }; nodePtr Tree; 8 3 14 1 5 7 10 12 19 16 23 17 Example: Binary Insertion Tree Each left offspring of a node has a value less than the node’s value Each right offspring of a node has a value greater than or equal to the node’s value Chapter 9 Abstract Data Types and Algorithms Page 106 Chapter 9 Abstract Data Types and Algorithms Page 106

107 Recursive Insertion into a Binary Insertion Tree
void Bin_Insert(nodePtr &Tree, int item) { if (Tree == NULL) nodePtr ptr = new node; ptr->value = item; ptr->left = NULL; ptr->right = NULL; } else if (item < Tree->value) Bin_Insert(Tree->left, item); else Bin_Insert(Tree->right, item); 8 3 14 1 5 7 10 12 19 16 23 17 Example: Where will a new node containing the integer 11 be inserted? 11 Chapter 9 Abstract Data Types and Algorithms Page 107 Chapter 9 Abstract Data Types and Algorithms Page 107

108 Recursive Traversal of a Binary Insertion Tree
void Inorder(nodePtr Tree) { if (Tree != NULL) Inorder(Tree->left); cout << Tree->value << endl; Inorder(Tree->right); } 1 3 5 7 8 10 12 Example: Apply Inorder to this binary insertion tree: 14 8 3 14 1 5 7 10 12 19 16 23 17 16 17 19 23 Chapter 9 Abstract Data Types and Algorithms Page 108 Chapter 9 Abstract Data Types and Algorithms Page 108

109 Abstract Data Types and Algorithms Abstract Data Types and Algorithms
What Does This Function Do To A Binary Tree? int Sumac(nodePtr Tree) { int leftbranch, rightbranch; if (Tree == NULL) return 0; else leftbranch = Sumac(Tree->left); rightbranch = Sumac(Tree->right); return leftbranch + rightbranch + Tree->value; } 125 13 5 20 34 22 7 9 15 51 61 34 22 31 Chapter 9 Abstract Data Types and Algorithms Page 109 Chapter 9 Abstract Data Types and Algorithms Page 109 9 15


Download ppt ""

Similar presentations


Ads by Google