Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6: Low-Level Programming Languages Chapter 6 Low-Level Programming Languages Page 51 In order to execute instructions on a CPU, those instructions.

Similar presentations


Presentation on theme: "Chapter 6: Low-Level Programming Languages Chapter 6 Low-Level Programming Languages Page 51 In order to execute instructions on a CPU, those instructions."— Presentation transcript:

1

2 Chapter 6: Low-Level Programming Languages Chapter 6 Low-Level Programming Languages Page 51 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)

3 Simplified Machine Language Chapter 6 Low-Level Programming Languages Page 52 Note that every instruction is sixteen bits (four hexadecimal digits) in length.

4 Sample Program Chapter 6 Low-Level Programming Languages Page CLoad register 0 with the integer 92 (hexadecimal 5C) 300EStore the contents of register 0 at main memory address 0E 205ALoad register 0 with the integer 90 (hexadecimal 5A) 300FStore the contents of register 0 at main memory address 0F 110ELoad register 1 with the bit pattern at main memory address 0E 120FLoad register 2 with the bit pattern at main memory address 0F 5012Add the contents of registers 1 & 2 and put the sum in register 0 300DStore the contents of register 0 at memory address 0D C000Halt execution In an advanced language, like C++, this program would be: void main() { int X, Y, Z; int X, Y, Z; X = 92; X = 92; Y = 90; Y = 90; Z = X + Y; Z = X + Y;}

5 Another Sample Program Chapter 6 Low-Level Programming Languages Page 54 How would we code this pseudocode with our machine language? Procedure negative (x) If x < 0 If x < 0 Then return 1 Then return 1 Else return 0 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.

6 Chapter 6 Low-Level Programming Languages Page 55 Procedure negative (x) If x < 0 If x < 0 Then return 1 Then return 1 Else return 0 Else return 0 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.

7 Chapter 6 Low-Level Programming Languages Page 56 To make programming easier to handle, special languages (unique to the kinds of computers running them) have been developed. 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”) 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. Assembly Language Example : LOADVAR R1,X LOADVAR R1,X LOADHEX R0,80 LOADHEX R0,80 AND R2,R0,R1 AND R2,R0,R1 JUMPEQ R0,R2,NEGATIVE JUMPEQ R0,R2,NEGATIVE LOADHEX R3,00 LOADHEX R3,00 JUMPEQ R0,R0,STOREIT JUMPEQ R0,R0,STOREIT NEGATIVE LOADHEX R3,01 STOREIT STORE R3, RESULT HALT HALT

8 Chapter 6 Low-Level Programming Languages Page 57 While assembly languages are easier to use than machine languages, they still share two big problems with machine languages. Assembly Language Problems 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. overall solution of the problem being tackled.

9 Chapter 7: Problem Solving and Algorithm Design Chapter 7 Problem Solving and Algorithm Design Page 58 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

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

11 Computer Algorithms Chapter 7 Problem Solving and Algorithm Design Page 60 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: 1.Semantics: The meaning of the step 2.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; var x, y integer; begin begin write(“Input your number: ”); write(“Input your number: ”); read(x); read(x); y = 2*x; y = 2*x; writeln(“The doubled number is ”, y); writeln(“The doubled number is ”, y); end. end.

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

13 Algorithm Alternatives Chapter 7 Problem Solving and Algorithm Design Page 62 It’s possible to devise many algorithms to solve the same problem. Procedure Sat1231B Set day_of_week to 12/31/2000 Set day_of_week to 12/31/2000 Set year to 2001 Set year to 2001 While (year < 2021) Do While (year < 2021) Do { If year is a leap year If year is a leap year Then increment day_of_week by 2 Then increment day_of_week by 2 Else increment day_of_week by 1 Else increment day_of_week by 1 If day_of_week is Saturday If day_of_week is Saturday Then display year as having a Saturday New Year’s Eve Then display year as having a Saturday New Year’s Eve Increment year by 1 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?

14 Program Modularity Chapter 7 Problem Solving and Algorithm Design Page 63 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

15 Advantages of Modular Programming Chapter 7 Problem Solving and Algorithm Design Page 64 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

16 Top-Down Design Chapter 7 Problem Solving and Algorithm Design Page 65 One common approach for designing programs is the top-down methodology. 1.Design a high-level solution to the programming problem.  This approach lends itself to modularity. 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 2.Consider each complicated subproblem as a separate programming problem. 3.Return to step #1 with each subproblem.  However, it may impose an artificial hierarchy on the tasks being performed.

17 Bottom-Up Design Chapter 7 Problem Solving and Algorithm Design Page 66 A newer approach for designing programs is the bottom-up methodology. 1.Separate each major task in the overall problem into an individual programming problem.  This approach produces reusable modules. 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 2.Develop cooperative programming solutions to the separate problems.  However, those modules may prove difficult to cobble together to solve bigger problems.

18 Chapter 8: Abstract Data Types and Algorithms Chapter 8 Abstract Data Types and Algorithms Page 67 Two keys to making computer software that works well: Organize data so it can be accessed and processed efficiently. 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. Develop algorithms that take advantage of the strengths of the programming language and the hardware to accomplish what the program is attempting to do.

19 Iteration Chapter 8 Abstract Data Types and Algorithms Page 68 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 Set test_name to first name in phonebook While (test_name is alphabetically before sought_name AND While (test_name is alphabetically before sought_name AND there are still more names in phonebook) Do there are still more names in phonebook) Do Set test_name to the next name in phonebook Set test_name to the next name in phonebook If test_name is sought_name If test_name is sought_name Then return the corresponding phone number Then return the corresponding phone number Else return “Unlisted” message Else return “Unlisted” message Procedure SeqSearch(phonebook, sought_name) Set test_name to first name in phonebook Set test_name to first name in phonebook While (test_name is alphabetically before sought_name AND While (test_name is alphabetically before sought_name AND there are still more names in phonebook) Do there are still more names in phonebook) Do Set test_name to the next name in phonebook Set test_name to the next name in phonebook If test_name is sought_name If test_name is sought_name Then return the corresponding phone number Then return the corresponding phone number Else return “Unlisted” message Else return “Unlisted” message When an algorithm involves repetitive actions, iteration (i.e., looping) may be a practical approach. 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.

20 Chapter 8 Abstract Data Types and Algorithms Page 69 Calling SeqSearch(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list below: NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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

21 Chapter 8 Abstract Data Types and Algorithms Page 70 Recursion Pseudocode to recursively take a base number to a specified power: Procedure Exponentiate(base, power) If base is 0 If base is 0 Then return 0 Then return 0 Else If power < 0 Else If power < 0 Then return Exponentiate(base, power+1)/base Then return Exponentiate(base, power+1)/base Else If power is 0 Else If power is 0 Then return 1 Then return 1 Else return base * Exponentiate(base, power-1) Else return base * Exponentiate(base, power-1) Procedure Exponentiate(base, power) If base is 0 If base is 0 Then return 0 Then return 0 Else If power < 0 Else If power < 0 Then return Exponentiate(base, power+1)/base Then return Exponentiate(base, power+1)/base Else If power is 0 Else If power is 0 Then return 1 Then return 1 Else return base * Exponentiate(base, power-1) Else return base * Exponentiate(base, power-1) 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. 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.

22 Chapter 8 Abstract Data Types and Algorithms Page 71 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 Set test_name to the middle name in phonebook If test_name is sought_name If test_name is sought_name Then return corresponding phone number Then return corresponding phone number Else If phonebook has only one remaining entry Else If phonebook has only one remaining entry Then return “Unlisted” message Then return “Unlisted” message If test_name is alphabetically before sought_name If test_name is alphabetically before sought_name Then apply BinarySearch to the portion of phonebook after test_name Then apply BinarySearch to the portion of phonebook after test_name Else apply BinarySearch to the portion of phonebook before test_name Else apply BinarySearch to the portion of phonebook before test_name Procedure BinarySearch(phonebook, sought_name) Set test_name to the middle name in phonebook Set test_name to the middle name in phonebook If test_name is sought_name If test_name is sought_name Then return corresponding phone number Then return corresponding phone number Else If phonebook has only one remaining entry Else If phonebook has only one remaining entry Then return “Unlisted” message Then return “Unlisted” message If test_name is alphabetically before sought_name If test_name is alphabetically before sought_name Then apply BinarySearch to the portion of phonebook after test_name Then apply BinarySearch to the portion of phonebook after test_name Else apply BinarySearch to the portion of phonebook before 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.

23 Chapter 9 Abstract Data Types and Algorithms Page 77 Chapter 8 Abstract Data Types and Algorithms Page 72 Calling BinarySearch(phonebook, sought_name) where sought_name is “Rubeus Hagrid” and phonebook is the list below: NameNameNumberNumber 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 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 Gilderoy Lockhart, so iterate again test_name is Rubeus Hagrid, so return NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 Cornelius Fudge, so iterate again NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 Hermione Granger, so iterate again NameNameNumberNumber 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 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 NameNameNumberNumber 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 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 NameNameNumberNumber 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 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

24 AddressContents : Memory cell 71 (hex 47) > :: A980 Memory cell 170 (hex AA) > AA85 : FE FF Chapter 8 Abstract Data Types and Algorithms Page 73 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. Example: int IQlist[100]; Conceptually, the array looks something like this: Index012…9899 Contents … However, in the computer’s RAM, space for 100 integers has been allocated something like this: An array is an indexed list of values of the same type.

25 Chapter 8 Abstract Data Types and Algorithms Page 74 Example: int GradeTable[3][5]; Conceptually, the array looks something like this: COLUMN # ROW # However, in the computer’s RAM, space for 15 integers has been allocated something like this: AddressContents : Space for element (0,0) > B25E (0,1) > B359 (0,2) > B464 (0,3) > B557 (0,4) > B65C (1,0) > B744 (1,1) > B85A (1,2) > B954 (1,3) > BA4E (1,4) > BB56 (2,0) > BC4D (2,1) > BD5F (2,2) > BE61 (2,3) > BF64 (2,4) > C058 : FF A multidimensional array is an indexed table of values of the same type, using more than one dimension.

26 Chapter 8 Abstract Data Types and Algorithms Page 75 Rather than reserving a contiguous block of memory to store a list, the linked list dynamically allocates memory as needed for list elements. Example: struct node; typedef node *nodePtr; struct node { int value; int value; nodePtr next; nodePtr next;}; nodePtr List; Conceptually, the linked list looks something like this: However, in the computer’s RAM, space for 4 integers has been allocated something like this: AddressContents 00 : rd item is at address B0 17B0 : 4E5E FF signifies the end of List 4FFF : List is located at 9A 9A61 2 nd item is at address 16 9B16 : B058 4 th item is at address 4E B14E : FF

27 Chapter 8 Abstract Data Types and Algorithms Page 76 Relative Advantages of Arrays & Linked Lists ArraysArrays 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  One-by-one searching required  Indexing facilitates searching  Sequential search only  Binary search possible if sorted  Tougher to conceptualize  Straightforward to program  Complicated garbage collection  Memory easily cleared after use

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

29 Chapter 8 Abstract Data Types and Algorithms Page 78 Comparison: Sequential Search Using an array Using a linked list int Search(int List[50], int ListSize, int ListSize, int soughtVal) int soughtVal){ int count; int count; bool found = false; bool found = false; count = 0; count = 0; while ((!found) && while ((!found) && (count < 50)) (count < 50)) { if (List[count] == if (List[count] == soughtVal) soughtVal) found = true; found = true; else else count++; count++; } if (found) if (found) return List[count]; return List[count]; else else return -1; return -1;} int Search(int List[50], int ListSize, int ListSize, int soughtVal) int soughtVal){ int count; int count; bool found = false; bool found = false; count = 0; count = 0; while ((!found) && while ((!found) && (count < 50)) (count < 50)) { if (List[count] == if (List[count] == soughtVal) soughtVal) found = true; found = true; else else count++; count++; } if (found) if (found) return List[count]; return List[count]; else else return -1; return -1;} int Search(nodePtr List, int soughtVal) int soughtVal){ nodePtr currPtr; nodePtr currPtr; bool found = false; bool found = false; currPtr = List; currPtr = List; while ((!found) && while ((!found) && (currPtr != NULL)) (currPtr != NULL)) { if (currPtr->value == if (currPtr->value == soughtVal) soughtVal) found = true; found = true; else else currPtr = currPtr->next; currPtr = currPtr->next; } if (found) if (found) return currPtr->value; return currPtr->value; else else return -1 return -1} int Search(nodePtr List, int soughtVal) int soughtVal){ nodePtr currPtr; nodePtr currPtr; bool found = false; bool found = false; currPtr = List; currPtr = List; while ((!found) && while ((!found) && (currPtr != NULL)) (currPtr != NULL)) { if (currPtr->value == if (currPtr->value == soughtVal) soughtVal) found = true; found = true; else else currPtr = currPtr->next; currPtr = currPtr->next; } if (found) if (found) return currPtr->value; return currPtr->value; else else return -1 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.

30 Chapter 8 Abstract Data Types and Algorithms Page 79 Sorting Algorithms 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 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 completely random list Speed with which it sorts a nearly sorted list Speed with which it sorts a nearly sorted list Amount of memory required to implement it Amount of memory required to implement it Ease with which it can be coded 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:

31 Chapter 8 Abstract Data Types and Algorithms Page 80 Selection Sort 1.Let k equal the size of your list 2.Let i equal the index of the first element of your list 3.Swap the smallest element in the last k elements with the i th element 4.Decrease k by one 5.Increase i by one 6.If k is still larger than one, repeat, starting at step #3 1.Let k equal the size of your list 2.Let i equal the index of the first element of your list 3.Swap the smallest element in the last k elements with the i th element 4.Decrease k by one 5.Increase i by one 6.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 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 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 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

32 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 Chapter 8 Abstract Data Types and Algorithms Page 81 Bubble Sort 1.Let k equal the size of your list 2.Let i equal the index of the first element of your list 3.Starting with the i th element of the list and moving down to the k th element, swap every consecutive pair of elements that is in the wrong order 4.Decrease k by one 5.Increase i by one 6.If k is still larger than one, repeat, starting at step #3 1.Let k equal the size of your list 2.Let i equal the index of the first element of your list 3.Starting with the i th element of the list and moving down to the k th element, swap every consecutive pair of elements that is in the wrong order 4.Decrease k by one 5.Increase i by one 6.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  Verdict: Tougher to program, little memory waste, inefficient in general (but could easily be modified to terminate early if a swap-less pass occurs) 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 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 

33 Chapter 8 Abstract Data Types and Algorithms Page 82 Quick Sort 1.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 2.Let pivot equal the value currently at index p of the list 3.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 4.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 5.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 1.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 2.Let pivot equal the value currently at index p of the list 3.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 4.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 5.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 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 pivot: 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 TiaHal 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 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 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 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 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 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 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 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 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 TiaHal 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 pivot: 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 TiaGus 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 Xon pivot: 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 TiaGus 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   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)

34 Chapter 8 Abstract Data Types and Algorithms Page 83 Example: 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. Initial Stack 3 After “Push 3” 53 After “Push 5” 853 After “Push 8” 53 After “Pop” 3 13 After “Push 1”

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

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

37 Chapter 8 Abstract Data Types and Algorithms Page 86 Example: 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. Initial Queue: F/R After Insert 7: 7 FR After Insert 4: 74 FR After Insert 2: 742 FR After Remove: 42 FR After Insert 5: 425

38 Chapter 8 Abstract Data Types and Algorithms Page 87 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(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; } 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; }

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

40 Chapter 8 Abstract Data Types and Algorithms Page 89 Example Implementation: struct node; typedef node *nodePtr; struct node { int value; int value; nodePtr left; nodePtr left; nodePtr right; nodePtr right;}; nodePtr 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: Binary Insertion Tree Each left offspring of a node has a value less than the node’s valueEach 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 valueEach right offspring of a node has a value greater than or equal to the node’s value

41 Chapter 8 Abstract Data Types and Algorithms Page 90 Recursive Insertion into a Binary Insertion Tree Example: Where will a new node containing the integer 11 be inserted? void Bin_Insert(nodePtr &Tree, int item) { if (Tree == NULL) if (Tree == NULL) { nodePtr ptr = new node; nodePtr ptr = new node; ptr->value = item; ptr->value = item; ptr->left = NULL; ptr->left = NULL; ptr->right = NULL; ptr->right = NULL; } else if (item value) else if (item value) Bin_Insert(Tree->left, item); Bin_Insert(Tree->left, item); else else Bin_Insert(Tree->right, item); Bin_Insert(Tree->right, item);} void Bin_Insert(nodePtr &Tree, int item) { if (Tree == NULL) if (Tree == NULL) { nodePtr ptr = new node; nodePtr ptr = new node; ptr->value = item; ptr->value = item; ptr->left = NULL; ptr->left = NULL; ptr->right = NULL; ptr->right = NULL; } else if (item value) else if (item value) Bin_Insert(Tree->left, item); Bin_Insert(Tree->left, item); else else Bin_Insert(Tree->right, item); Bin_Insert(Tree->right, item);}

42 Chapter 8 Abstract Data Types and Algorithms Page 91 Recursive Traversal of a Binary Insertion Tree Example: Apply Inorder to this binary insertion tree: void Inorder(nodePtr Tree) { if (Tree != NULL) if (Tree != NULL) { Inorder(Tree->left); Inorder(Tree->left); cout value value << endl; Inorder(Tree->right); Inorder(Tree->right); }} void Inorder(nodePtr Tree) { if (Tree != NULL) if (Tree != NULL) { Inorder(Tree->left); Inorder(Tree->left); cout value value << endl; Inorder(Tree->right); Inorder(Tree->right); }}

43 Chapter 8 Abstract Data Types and Algorithms Page 92 What Does This Function Do To A Binary Tree? int Sumac(nodePtr Tree) { int leftbranch, rightbranch; int leftbranch, rightbranch; if (Tree == NULL) if (Tree == NULL) return 0; return 0; else else { leftbranch = Sumac(Tree->left); leftbranch = Sumac(Tree->left); rightbranch = Sumac(Tree->right); rightbranch = Sumac(Tree->right); return leftbranch + rightbranch + Tree->value; return leftbranch + rightbranch + Tree->value; }} int Sumac(nodePtr Tree) { int leftbranch, rightbranch; int leftbranch, rightbranch; if (Tree == NULL) if (Tree == NULL) return 0; return 0; else else { leftbranch = Sumac(Tree->left); leftbranch = Sumac(Tree->left); rightbranch = Sumac(Tree->right); rightbranch = Sumac(Tree->right); return leftbranch + rightbranch + Tree->value; return leftbranch + rightbranch + Tree->value; }}

44 Chapter 9: High-Level Programming Languages Chapter 9 High-Level Programming Languages Page 93 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. 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! Example: int negative (int x) { if (x < 0) if (x < 0) return 1; return 1; else else return 0; return 0;}

45 Compilation Chapter 9 High-Level Programming Languages Page 94 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. Source Program (in TGL) LexicalAnalysis Parsing CodeGeneration Object Program (in Machine Language) 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).

46 Linking and Loading Chapter 9 High-Level Programming Languages Page 95 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 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. CompileCompile LinkLink Load Module Load Module Load Executable Program Executable Program

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

48 Data Types Chapter 9 High-Level Programming Languages Page 97 Data types are used to specify how the bit patterns used to represent data should be interpreted by the program. int count; float price; bool flag; Scalar: Single-valued data types (e.g., integer, floating-point, character, boolean) 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]; char name[30]; int examScore[5]; int examScore[5]; int quizScore[25]; int quizScore[25]; int paperScore[2]; int paperScore[2]; char letterGrade; char letterGrade;}; Student FALL111[25];

49 Imperative Statements - Part One Chapter 9 High-Level Programming Languages Page 98 Assignment statements are used to assign a value to a variable. x = 127; Input/output statements are used to retrieve external values (input) and to file away or print information (output). cout << “Enter user’s name: ”; ccountEmx ccountEmx ccountEmx ccountEmx ccountEmx count = count + 1; E = m * c * c; nextDataValue nextDataValue25nextDataValue25 dataFilepositiveFile cin >> username; dataFile >> nextDataValue; if (nextDataValue > 0) positiveFile << nextDataValue; positiveFile << nextDataValue;

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

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

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

53 Object-Oriented Programming Chapter 9 High-Level Programming Languages Page 102 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.

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


Download ppt "Chapter 6: Low-Level Programming Languages Chapter 6 Low-Level Programming Languages Page 51 In order to execute instructions on a CPU, those instructions."

Similar presentations


Ads by Google