10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

Slides:



Advertisements
Similar presentations
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Advertisements

Chapter 9: Searching, Sorting, and Algorithm Analysis
9-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Chapter 8 Search and Sort Asserting Java ©Rick Mercer.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Chapter 8 ARRAYS Continued
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Big Oh Algorithm Analysis with
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 16: Searching, Sorting, and the vector Type.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 8 Arrays and Strings
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
CSC 211 Data Structures Lecture 13
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
Data Structures and Algorithms Searching Algorithms M. B. Fayek CUFE 2006.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Asserting Java © Rick Mercer Chapter 7 The Java Array Object.
© Rick Mercer Chapter 7 The Java Array Object.  Some variables store precisely one value: a double stores one floating-point number a double stores one.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Algorithm Analysis with Big Oh ©Rick Mercer. Two Searching Algorithms  Objectives  Analyze the efficiency of algorithms  Analyze two classic algorithms.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 8 Search and Sort
Chapter 10 Vectors Computing Fundamentals with C++ 3rd Edition
Chapter 12 Pointers and Memory Management
Chapter 4 Implementing Free Functions
Chapter 9 File Streams Computing Fundamentals with C++ 3rd Edition
Mr. Dave Clausen La Cañada High School
Computing Fundamentals with C++
Chapter 9: Data Structures: Arrays
Presentation transcript:

10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Computing Fundamentals with C++, Object-Oriented Programming and Design by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact.

10-2 Chapter 10 Vectors  Chapter Objectives  Construct vector objects that can store collections of like objects e.g. one vector can store many numbers  Implement algorithms to process a collection of objects e.g. display all elements, find min/max  Use the sequential search algorithm to locate a specific element in a vector  Pass vector objects to functions –Exercises –Programming Projects

10-3 Second Part of Chapter 10  Part II  Sort vector elements into ascending or descending order  Understand the binary search algorithm.  Implement a container class with a vector data member PREREQUISITE: Chapter 6 –Exercises –Programming Projects –Note: There are two sets of exercises and programming projects

10-4  Some objects store precisely one value:  a double store one number  an int stores one integer  Other objects store more than one (possibly dissimilar) values, for example:  bankAccount objects store a string and a double  What does a string object store?  not sure 10.1 The Standard C++ vector Class

10-5 Recall string objects  Any string object stores a collection of characters (more than one value)  individual characters are referenced with [ ] cout << myName[0]; // reference the 1st char  This chapter introduces vector objects which  stores a collection of similar objects.  Individual objects are accessed through subscripts []

10-6 vectors are generic  This code declares a vector named x vector x( 100, 0.0 ); vector x( 100, 0.0 ); x[0] = 90.5; x[0] = 90.5; x[1] = 77.34; x[1] = 77.34;  that has the capacity to store 100 numbers  the first two elements store 90.5 and  the other 98 elements are 0.0 the 2nd constructor argument  We can have a vector of almost any class of objects the default constructor is used here vector x( 100 ); vector x( 100 );

10-7 vectors are...  A vector is homogeneous because all objects stored under one vector name must be of the same class  vectors may be sized (at compile-time) or dynamically sized (at runtime)  we can set the capacity of a vector at runtime cout << "Number of students?"; cout << "Number of students?"; cin >> n; cin >> n; vector university(n); vector university(n); // default constructor called for n elements // default constructor called for n elements

10-8 General form of vector construction vector identifier ( capacity, initial-value ) ;  class specifies the class of objects stored in the vector object  identifier is the name of the vector object  capacity is an integer expression specifying the maximum number of objects that can be stored  initial-value is the value that every element will be set to. The initial value is optional  If the initial-value is omitted, the default constructor initializes every object in the vector –Suggestion: if class is int or double, specify an initial-value

10-9 Example Constructions  A vector that stores up to 8 numbers, which are all initialized to 0.0 vector x(8, 0.0); vector x(8, 0.0);  A vector that stores 500 string objects: vector name(500); vector name(500);  A vector that store 1,000 integers, which are all initialized to -1): vector test(1000, -1); vector test(1000, -1);  A vector that stores up to 100 bankAccounts vector customer(100); vector customer(100);

Accessing Individual Elements in the Collection  Individual array elements are referenced through subscripts of this form: vector-name [ int-expression ] vector-name [ int-expression ]  int-expression is an integer that should be in the range of 0..capacity-1.  Examples: x[0] // Pronounced x sub 0 x[0] // Pronounced x sub 0 name[5] // Pronounced name sub 5 name[5] // Pronounced name sub 5 test[99] // Pronounced test sub 99 test[99] // Pronounced test sub 99 customer[12] // Pronounced customer sub 12 customer[12] // Pronounced customer sub 12

10-11 Assignment and input operations work on individual vector elements #include // for the standard vector class #include #include using namespace std; int main() { int n = 5; int n = 5; vector x(n, 0); vector x(n, 0); x[0] = 1; // Assume input of x[0] = 1; // Assume input of cout << "Enter two integers: "; // 2 5 cout << "Enter two integers: "; // 2 5 cin >> x[1] >> x[2]; cin >> x[1] >> x[2]; x[3] = x[0] + x[2]; x[3] = x[0] + x[2]; x[4] = x[3] - 1; x[4] = x[3] - 1; for(int j = 0; j < n; j++) // LOOP OUTPUT? for(int j = 0; j < n; j++) // LOOP OUTPUT? { cout << x[j] << endl; cout << x[j] << endl; } return 0; return 0;}

10-12 The vector after modifying its state

Vector Processing with Determinate for Loops  The need often arises to access all meaningful elements e.g. sum the first n elements in test vector test(100, -99.9); vector test(100, -99.9); test[0] = 64; test[0] = 64; test[1] = 82; test[1] = 82; // … assume 21 additional assignments … // … assume 21 additional assignments … test[23] = 97; test[23] = 97; int n = 24; int n = 24; double sum = 0.0; double sum = 0.0; for(int j = 0; j < n; j++) for(int j = 0; j < n; j++) { sum += test[j]; sum += test[j]; }

Processing the First n Elements of a vector  A vector often has capacity larger than need be  The previous example only used the first 24 of a potential 100 elements.  The textbook often uses n to represent the number of initialized and meaningful elements  The previous loop did not add x[24] nor x[25], nor x[99] all of which were  vectors can be sized at runtime and even resized later

10-15 vector processing in this text book  Example vector processing you will see  displaying some or all vector elements  finding the sum, or average, or highest of all vector elements  searching for a given value in the vector  arranging elements in a certain order  ordering elements from largest to smallest  or alphabetizing a vector of strings from smallest to largest

Out of Range Subscript Checking  Most vector classes don't care if you use subscripts that are out of range vector name(1000); vector name(1000); name[-1] = "Subscript too low"; name[-1] = "Subscript too low"; name[ 0] = "This should be the first name"; name[ 0] = "This should be the first name"; name[999] = "This is the last good subscript"; name[999] = "This is the last good subscript"; name[1000] = "Subscript too high"; name[1000] = "Subscript too high";  These other vector classes let you crash your computer instead! segmentation or general protection faults

10-17 With MSVC in Windows 95  The standard vector class distributed with this Microsoft's Compiler also gracefully terminates the program with this:

10-18 Range Checking Optional Demo: rangerr.cpp See if you can get the safe vector  Recommendation: use the vector class from this textbooks disk  copy vector into your working folder  including it this way works on Unix systems: #include "vector" // for a safe vector class #include "vector" // for a safe vector class  Or you could change your include path settings to search the current folder first and then write this #include // for a safe vector class #include // for a safe vector class

vector::capacity and vector::resize  The proper capacity of a vector is usually an issue  There are two useful functions to help int vector::capacity() void vector::resize(int newSize)

10-20 vector::capacity and vector::resize #include // for the standard vector class using namespace std; int main() { vector v1; // v1 cannot store any elements vector v1; // v1 cannot store any elements vector v2(5); vector v2(5); cout << "v1 can hold " << v1.capacity() << endl; cout << "v1 can hold " << v1.capacity() << endl; cout << "v2 can hold " << v2.capacity() << endl; cout << "v2 can hold " << v2.capacity() << endl; v1.resize(22); v1.resize(22); cout << "v1 can now hold " << v1.capacity() << endl; cout << "v1 can now hold " << v1.capacity() << endl; return 0; return 0;}Output: v1 can hold 0 v2 can hold 5 v1 can now hold 22

10-21 What happens during a resize message?  When a vector is resized this book's safe vector  and the new size is bigger than the old size  the existing elements are intact  and the new size is smaller than the old size  the elements in the highest locations are truncated

Sequential Search  We often need to search for data stored in a vector (a phone number, an inventory item, an airline reservation, a bank customer)  We will simplify the search algorithm by searching only for strings  Imagine however that the vector may be a collection of bankAccounts, students, inventory, sales, employees, or reservations

10-23 Sequential search algorithm  There are many searching algorithms  We will study the sequential search algorithm with a simple collection of strings  Here is the first cut at the algorithm: Initialize a vector of strings (call it myFriends) Initialize a vector of strings (call it myFriends) Get the name to search for (call it searchName) Get the name to search for (call it searchName) Try to find searchName Try to find searchName Report on success or failure of search Report on success or failure of search

10-24 The array being searched  We'll use this data in our searches: vector myFriends(10); vector myFriends(10); int n = 5; int n = 5; myFriends[0] = "DEBBIE"; myFriends[0] = "DEBBIE"; myFriends[1] = "JOEY"; myFriends[1] = "JOEY"; myFriends[2] = "BOBBIE"; myFriends[2] = "BOBBIE"; myFriends[3] = "SUSIE"; myFriends[3] = "SUSIE"; myFriends[4] = "MIKEY"; myFriends[4] = "MIKEY";  Note: We often have unused elements in a vector. For example, we could add 5 more strings to the collection named myFriends.

10-25 The Possibilities?  searchName is in the vector  searchName is not in the vector  Now: write the code that stores the index (subscript) of searchName in myFriends string searchName; string searchName; cout << "Enter name to search for: "; cout << "Enter name to search for: "; cin >> searchName; cin >> searchName;Dialogue Enter name to search for: BOBBIE Enter name to search for: BOBBIE

10-26 Sequential Search // assert: searchName is in myFriends // --if it is not, watch out! // Search for searchName starting at myFriends[0] int subscript = 0; while(searchName != myFriends[subscript]) { // assert: searchName has not yet been found subscript++; // compare to next vector element }

10-27 Example search for "BOBBIE"

10-28 Report success or failure // Report success or failure (see changes below) if(subscript < n) cout << myFriends[subscript] << " found"; else cout << searchName << " not found";  Question: What would happen if searchName was not amongst myFriends ?

10-29 What if searchName isn't there?

10-30 Active Learning  Rewrite the sequential search algorithm so it works even if searchName is not in the vector myFriends int subscript = 0; int subscript = 0; while( ____________________________ while( ____________________________ ____________________________ ) ____________________________ ) { subscript++; subscript++; }

Messages to individual objects in a vector  General form for sending a message to an individual object in a vector: vector-name [ subscript ]. message  Examples: vector name(1000); vector name(1000); vector acct(10000); vector acct(10000); name[3] = "Any string"; name[3] = "Any string"; int n( name[3].length() ); int n( name[3].length() ); acct[99] = bankAccount("Westphall", ); acct[99] = bankAccount("Westphall", ); acct[99].withdraw(100.00); acct[99].withdraw(100.00); cout << acct[99].balance() << endl; cout << acct[99].balance() << endl;

Initializing a vector of Objects with File Input  A vector is often initialized with file input  For example, might need to initialize a data base of bank customers with this file input: Cust AnyName AnyName Austen Austen Chelsea Chelsea Kieran Kieran Cust Cust Note: Seven lines are omitted Note: Seven lines are omitted... Cust Cust

10-33 Some preliminaries // Initialize a vector of bankAccounts through file input // Initialize a vector of bankAccounts through file input #include // for class ifstream #include // for class ifstream #include // for cout #include // for cout #include // for the standard vector class #include // for the standard vector class #include "baccount" // for class bankAccount #include "baccount" // for class bankAccount int main() int main() { ifstream inFile( "bank.dat" ); ifstream inFile( "bank.dat" ); if( ! inFile ) if( ! inFile ) { cout << "*Error* file 'bank.dat' not found" << endl; cout << "*Error* file 'bank.dat' not found" << endl; } else else {

10-34 Reading until end of file vector account( 20 ); vector account( 20 ); string name; string name; double balance = 0.0; double balance = 0.0; int n = 0; int n = 0; int j = 0; int j = 0; while( ( inFile >> name >> balance ) while( ( inFile >> name >> balance ) && ( n < account.capacity() ) ) && ( n < account.capacity() ) ) { // Create and store a new bankAccount in next location // Create and store a new bankAccount in next location account[ n ] = bankAccount( name, balance ); account[ n ] = bankAccount( name, balance ); // Increase initialized accounts and // Increase initialized accounts and // get ready to locate the next new bankAccount // get ready to locate the next new bankAccount n++; n++; } } // end else Optional Demo: file2vec.cpp

vector Argument/Parameter Associations by example void foo( vector acct ) void foo( vector acct ) { // VALUE parameter (should not be used with vectors) { // VALUE parameter (should not be used with vectors) // all elements of acct are copied // all elements of acct are copied // after allocating the additional memory // after allocating the additional memory } void foo( vector & acct ) void foo( vector & acct ) { // REFERENCE parameter ( allows changes to argument) { // REFERENCE parameter ( allows changes to argument) // Only a pointer the acct is copied. // Only a pointer the acct is copied. // A change to acct changes the argument // A change to acct changes the argument } void foo( const vector & acct ) void foo( const vector & acct ) { // CONST REFERENCE parameter (for efficiency and safety) { // CONST REFERENCE parameter (for efficiency and safety) // Only a reference to the acct is copied (4 bytes) // Only a reference to the acct is copied (4 bytes) // A change to acct does NOT change the argument // A change to acct does NOT change the argument }

10-36 Example vector pass vector by reference void init(vector & x, int & n) { n = 4; x.resize(n); x[0] = 0; x[1] = 11; x[2] = 22; x[3] = 33; } int main() { vector test; int n = 0; init(test, n); // aVector has a capacity of 4

Sorting  Sorting: the process of arranging vector elements into ascending or descending order:  Ascending (where x is a vector object): x[0] <= x[1] <= x[2] <=... <= x[n-2] <= x[n-1] x[0] <= x[1] <= x[2] <=... <= x[n-2] <= x[n-1]  Descending: x[0] >= x[1] >= x[2] >=... >= x[n-2] >= x[n-1] x[0] >= x[1] >= x[2] >=... >= x[n-2] >= x[n-1]  Here's the data used in the next few slides:

10-38 Swap largest with the first // Swap the largest element with the first top = 0 largestIndex = top for j ranging from top+1 through n - 1 { if test[ j ] > test[ largestIndex ] then if test[ j ] > test[ largestIndex ] then largestIndex = j largestIndex = j} // Question: What is largestIndex now __________? swap test[ largestIndex ] with test[ top ]

10-39 Selection sort algorithm  Now we can sort the entire vector by changing top from 0 to n-2 with this loop for (top = 0; top < n-1; top++) for each subvector, get the largest on top for each subvector, get the largest on top  The top moves down one vector position each time the largest is placed on top  Eventually, we get a sorted vector

10-40 Trace selection sort Optional Demo: sort.cpp Optional Demo: sort.cpp

Binary Search  We'll see that binary search can be a more efficient algorithm for searching  It works only on sorted arrays like this  Compare the element in the middle  if that's the target, quit and report success  if the key is smaller, search the array to the left  otherwise search the array to the right  This process repeats until we find the target or there is nothing left to search

10-42 Binary Search Harry Bob Carl Froggie Gene Harry Igor Debbie Evan a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] low mid high low mid high Judy Datareference pass 1 pass 2

10-43 How fast is Binary Search?  Best case: 1 comparison  Worst case: when the target is not there  At each pass, the live portion of the array (where we need to search) is narrowed to half the previous size  The series proceeds like this:  n, n/2, n/4, n/8,...  Each term in the series represents one comparison How long does it take to get to 1?  This will be the number of comparisons

10-44 Comparing O(n) sequential search to O(log n) binary search Rates of growth and logarithmic functions

10-45 Graph Illustrating Relative Growth n f(n) n log n

10-46 Defective Binary Search  Binary search sounds simple, but it's tricky consider this code int binarySearch(const vector & a, int binarySearch(const vector & a, int n, int target) int n, int target) { // pre: array a is sorted from a[0] to a[n-1] { // pre: array a is sorted from a[0] to a[n-1] int first = 0, last = n-1, int mid; int first = 0, last = n-1, int mid; while(first <= last) while(first <= last) { mid = (first+last)/2; mid = (first+last)/2; if(target == a[mid]) if(target == a[mid]) return mid; // found target return mid; // found target else if(target < a[mid]) else if(target < a[mid]) last = mid; // must be that target > a[mid] last = mid; // must be that target > a[mid] else else first = mid; // must be that target > a[mid] first = mid; // must be that target > a[mid] } return -1; // use -1 to indicate item not found return -1; // use -1 to indicate item not found }

10-47 Bob Carl Froggie Debbie Evan a[0] a[1] a[2] a[3] a[4] low mid high low mid high Data pass 1 pass 2 pass 3 pass 4... Search for "Duckie" What goes wrong? Fix code on previous slide low mid high low... mid... high... How do we fix this defective binary search ? _____? Optional Demo: binserch.cpp