Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 12 Manipulating Larger Quantities of Data.

Similar presentations


Presentation on theme: "An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 12 Manipulating Larger Quantities of Data."— Presentation transcript:

1 An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 12 Manipulating Larger Quantities of Data

2 Objectives In this chapter, you will learn about: The need for sorting data The bubble sort algorithm Sorting data in parallel arrays Sorting objects The insertion sort algorithm Multidimensional arrays Indexed files and linked lists 2An Object-Oriented Approach to Programming Logic and Design

3 Understanding the Need for Sorting Data Data record storage – Always in some sort of order – One record first, another second, and so on Sequential order – Records arranged one after another based on value of a particular field Records stored in random order – Still in some order – Probably not desirable for processing or viewing 3An Object-Oriented Approach to Programming Logic and Design

4 Understanding the Need for Sorting Records (cont’d) Sorting – Placing data in order – Sort is based on contents of one or more fields Types of sorting – Ascending order Arranging records from lowest to highest value – Descending order Arranging records from highest to lowest value 4An Object-Oriented Approach to Programming Logic and Design

5 Understanding the Need for Sorting Data (cont’d) Examples of situations in which sorting is needed – Student records In ascending order by student ID number Goal: descending order by credit hours – Customer records In ascending order by customer number Goal: descending order by amount owed – Salesperson records In alphabetical order by last name Goal: sort based on annual sales amount 5An Object-Oriented Approach to Programming Logic and Design

6 Understanding the Need for Sorting Data (cont’d) Computers sort data by comparing numeric values Alphabetic sorts (numeric sorts) Everything stored in computer as zeros and ones – In every popular computing coding scheme “B” numerically one greater than “A” “y” numerically one less than “z – “A” greater or smaller than “a”? Ultimately computer-dependent Use input data with consistent capitalization Convert data to consistent capitalization before sort 6An Object-Oriented Approach to Programming Logic and Design

7 Understanding the Need for Sorting Data (cont’d) Writing sort program – Not likely needed Can purchase prewritten or “canned” sorting programs Database software provides built-in sort methods Benefit of understanding sorting process – Provides ability to write special-purpose sort – Improves array manipulation skills 7An Object-Oriented Approach to Programming Logic and Design

8 Using the Bubble Sort Algorithm Simplest sorting technique to understand Possible record arrangements – Ascending or descending order List items compared in pairs – Encounter out of order item Swap value with item below Ascending bubble sort – After each adjacent item pair compared once Largest item “sinks” to bottom Smallest item “rises” to top Sometimes called “sinking sort” 8An Object-Oriented Approach to Programming Logic and Design

9 Using the Bubble Sort Algorithm (cont’d) Algorithm – List of instructions that accomplish a task – Bubble Sort: example of a sorting algorithm Swapping two values – Central to most sorting techniques – Reverse positions Set first variable equal to value of the second Set second variable equal to value of the first Temporary variable created – Holds copy of one value to prevent data loss 9An Object-Oriented Approach to Programming Logic and Design

10 Using the Bubble Sort Algorithm (cont’d) 10An Object-Oriented Approach to Programming Logic and Design Program segment that swaps two values Figure 12-1

11 Figure 12-2 11An Object-Oriented Approach to Programming Logic and Design Declares constant to hold array’s size Declares an array to hold five scores main() method calls three methods o Input scores o Sort array o Display sorted test scores Sorts five student test scores in ascending order

12 Figure 12-3 12An Object-Oriented Approach to Programming Logic and Design Figure 12-3 illustrates fillArray() method – Receives parameters for array and its size – Subscript initialized to zero – Each array element filled – Returns control to main program after five scores are stored in array

13 Figure 12-4 Figure 12-4 illustrates an incomplete sortArray() method – Sorts array elements by making series of comparisons of adjacent element values – Swaps as necessary using swap() method – Uses constant COMPS for loop control 13An Object-Oriented Approach to Programming Logic and Design

14 Using the Bubble Sort Algorithm (cont’d) 14An Object-Oriented Approach to Programming Logic and Design Illustrates swap() method Swaps any two adjacent elements in the score array Figure 12-5

15 Figure 12-6 15An Object-Oriented Approach to Programming Logic and Design Using the Bubble Sort Algorithm (cont’d) Figure 12-6 illustrates steps accomplished in the first loop of the bubble Sort

16 16An Object-Oriented Approach to Programming Logic and Design Figure 12-7 illustrates pseudocode and flowchart for complete sortArray() logic Figure 12-7

17 Using a Bubble Sort (cont’d) General Rules for making comparisons with bubble sort – Greatest number of pair comparisons is one less than array size (use inner loop) – Number of times to process the list is one less than array size (use outer loop) – Example: To sort a 10-element array, make nine comparisons on each of nine rotations through the loop, executing the score comparison statement 81 times 17An Object-Oriented Approach to Programming Logic and Design

18 Figure 12-8 18An Object-Oriented Approach to Programming Logic and Design Figure 12-8 illustrates displayArray() method which displays the sorted array contents

19 Sorting a List of Variable Size Sorted list size may vary – Array does not need to be full – Count the number of scores as they are inputted into the array Store count value in variable – fillArray() method passes number of scores entered back to calling program – Methods manipulate only the array elements the user entered 19An Object-Oriented Approach to Programming Logic and Design

20 20 Figure 12-9 illustrates tracking number of elements stored in array Figure 12-9

21 An Object-Oriented Approach to Programming Logic and Design21 sortArray() method in SortScores2 class Figure 12-9 (cont’d)

22 An Object-Oriented Approach to Programming Logic and Design22 swap() method SortScores2 class Figure 12-9 (cont’d)

23 23An Object-Oriented Approach to Programming Logic and Design Pseudocode for SortScores2 class Figure 12-9 (cont’d)

24 Reduce Unnecessary Comparisons – Stop pair comparisons One element sooner on each pass through array Avoids comparing already-in-place values – Figure 12-10 Creates new variable: pairsToCompare After each pass through list, variable reduced by 1 24An Object-Oriented Approach to Programming Logic and Design Figure 12-10

25 Refining the Bubble Sort to Reduce Unnecessary Passes Improve bubble sort – Reduce number of passes through the array Many passes required if array elements are badly out of order Few passes may be required if elements are nearly in order Once elements are in order, no swaps occur in subsequent passes – Possible remedy: Add flag variable Set to “continue” if any element pairs swapped Set to “finished” if no swaps made “Finished” indicates all elements correctly sorted 25An Object-Oriented Approach to Programming Logic and Design

26 26 Figure 12-11 illustrates a method that sorts scores and uses a switchOccurred flag Figure 12-11

27 Sorting Data Stored in Parallel Arrays Data in parallel arrays contain related data in the same relative position in each array As one array is sorted, related data in other arrays must be moved Figure 12-12 illustrates parallel arrays containing student names and test scores 27An Object-Oriented Approach to Programming Logic and Design Figure 12-12

28 Figure 12-13 28An Object-Oriented Approach to Programming Logic and Design Sorting Data Stored in Parallel Arrays (cont’d) Figure 12-13 shows the swap() module for a program that sorts name array values and moves score array values accordingly

29 Sorting Objects One approach to sorting arrays of objects – Make comparisons on an attribute of the objects Use the method in the class that “gets” that attribute 29An Object-Oriented Approach to Programming Logic and Design – Figure 12-14 shows a Student class that contains getIdNumber() method – Comparison determines whether two adjacent elements are out of order stuArray[x].getIdNumber() > stuArray[x+1].getIdNumber() Figure 12-14

30 Sorting Objects (cont’d) Second approach to sorting arrays of objects 30An Object-Oriented Approach to Programming Logic and Design – Comparison determines whether two adjacent elements are out of order: stuArray[x].isGreater(stuArray[x+1] – Method can be used in any sorting algorithm that works with simple numeric values –Add a method to the class similar to isGreater() method shown in Figure 12-15 Figure 12-15

31 Using the Insertion Sort Algorithm Look at each list element one at a time If element is out of order relative to any items earlier in the list – Move each earlier item down one position – Insert test element Similar to technique used to sort objects manually 31An Object-Oriented Approach to Programming Logic and Design

32 Figure 12-16 shows pseudocode and flowchart for insertionSort() method – Performs an ascending insertion sort using a five- element array named score 32An Object-Oriented Approach to Programming Logic and Design Figure 12-16

33 Using the Insertion Sort Algorithm (cont’d) Figure 12-17 illustrates steps used in the insertion sort 33An Object-Oriented Approach to Programming Logic and Design Figure 12-17

34 Using Multidimensional Arrays Arrays – Series or list of values – Have same name and data type – Values referenced by subscript (index) One-dimensional (single-dimensional) array – Elements accessed using single subscript 34An Object-Oriented Approach to Programming Logic and Design

35 Using Multidimensional Arrays (cont’d) Table 12-1 shows rent amounts for apartments on different floors (0 – basement) Can locate value in an array with one subscript 35An Object-Oriented Approach to Programming Logic and Design

36 Using Multidimensional Arrays (cont’d) Two-dimensional arrays – Used to represent values in a table or a grid – Contains two dimensions: height and width Table 12-2 – Rent schedule based on floor and number of bedrooms An Object-Oriented Approach to Programming Logic and Design36

37 Using Multidimensional Arrays (cont’d) 37An Object-Oriented Approach to Programming Logic and Design Figure 12-18 – Shows how the one-dimensional and two-dimensional rent arrays might appear in computer memory Figure 12-18

38 Using Multidimensional Arrays (cont’d) Declaring arrays – One-dimensional Single set of square brackets follows array type and name – Two-dimensional Two sets of square brackets follows array type and name First set of brackets denotes number of rows, second set denotes number of columns 38An Object-Oriented Approach to Programming Logic and Design

39 Figure 12-19 39An Object-Oriented Approach to Programming Logic and Design Figure 12-19 shows the pseudocode and flowchart for a program that displays rent for apartments based on floor location and number of bedrooms

40 Figure 12-20 Using Multidimensional Arrays (cont’d) Three-dimensional arrays – Uses three subscripts to access value Row Column Page 40An Object-Oriented Approach to Programming Logic and Design Shows rental fees for multiple multi-story apartment buildings according to number of bedrooms

41 Using Indexed Files and Linked Lists Sorting large numbers of data records takes considerable time and computer memory Physical order – “Real” order of storage – Example: index cards with friends’ names in a stack Logical order – A virtual order based on any criterion – Usually more efficient than physical order to store and access records 41An Object-Oriented Approach to Programming Logic and Design

42 Using Indexed Files Index – Involves identifying a key field for each record Key field has contents that make the record unique Examples: product number or employee number – Store a list of key fields paired with address of corresponding data record Use index to find records in order based on their addresses – Allows use of a random-access storage device Each record can be placed in any physical location on disk Example: Figure 12-21 42An Object-Oriented Approach to Programming Logic and Design

43 Figure 12-21 Using Indexed Files (cont’d) 43An Object-Oriented Approach to Programming Logic and Design Figure 12-21 stores an index on a portion of a disk Address in index refers to other locations on disk Removing a record from an indexed file – Record does not have to be physically removed – Its reference can be deleted from the index

44 Using Linked Lists Linked list – Structure in memory that has one extra data field in each record – Field contains memory address of next item in list Add new record to a linked list – Search through list for correct logical location of new record 44An Object-Oriented Approach to Programming Logic and Design Each record contains a nextCustAddress field

45 Using Linked Lists (cont’d) Steps to add new customer to the list in Table 12-3 (Name: Newberg and ID number: 245) – Create variable named currentAddress and store the address of the first record in the list: (0000) – Compare new customer’s ID: 245 with current record’s ID – Since 245 > 111, save the first customer’s address in a variable named saveAddress – Then store the address of the next logical customer (7200) in the currentAddress variable 45An Object-Oriented Approach to Programming Logic and Design

46 Using Linked Lists (cont’d) Steps to add new customer to the list in Table 12-3 (cont’d) (Name: Newberg and ID number: 245) – Examine second customer record (one at address 7200) – Compare Newberg’s ID: 245 with ID stored at currentAddress : 222 – Value 245 is higher, so save the current address: (7200), in saveAddress, and store its nextCustAddress field: (4400) in the currentAddress variable 46An Object-Oriented Approach to Programming Logic and Design

47 Using Linked Lists (cont’d) Steps to add new customer to the list in Table 12-3 (cont’d) (Name: Newberg and ID number: 245) – Compare Newberg’s ID: 245 with 333, which is the ID at currentAddress (4400) – Value 245 is lower, so customer 245 should logically precede customer 333 – Set nextCustAddress field in Newberg’s record to (4400), which is the address of customer 333 – Set nextCustAddress field of the record located at saveAddress to Newberg’s address (8400) 47An Object-Oriented Approach to Programming Logic and Design

48 Using Linked Lists (cont’d) 48An Object-Oriented Approach to Programming Logic and Design To remove the record of customer 333 from linked list – Change Newberg’s nextCustAddress field to the value in Silver’s nextCustAddress field More sophisticated linked lists – Store two additional fields One stores address of next record; the other, the previous record Allows list to be accessed either forward or backward Shows table updated with new customer

49 Summary Data records sorted based on field contents – Ascending or descending order Bubble sort – List items compared in pairs Swap with item below – Ascending sort: largest items “sink” to bottom Improve bubble sort – Eliminate unnecessary comparisons – Eliminate unnecessary passes 49An Object-Oriented Approach to Programming Logic and Design

50 Summary (cont’d) Two-dimensional arrays – Have rows and columns of values – Two subscripts are used to access an element Many languages support arrays with even more dimensions Index or linked list – Access data records in a logical order that differs from physical order – Index uses a key field and physical address – Linked list uses an extra field containing next record’s address 50An Object-Oriented Approach to Programming Logic and Design


Download ppt "An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 12 Manipulating Larger Quantities of Data."

Similar presentations


Ads by Google