Introduction to Programming (in C++) Vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

Introduction to Programming (in C++) Subprograms: procedures and functions Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Introduction to Programming (in C++) Advanced examples Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Introduction to Programming (in C++) Numerical methods I Jordi Cortadella Dept. of Computer Science, UPC.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
CSE202: Lecture 14The Ohio State University1 Arrays.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Introduction to Programming (in C++) Data and statements Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Reasoning with invariants Jordi Cortadella Department of Computer Science.
Matrices Jordi Cortadella Department of Computer Science.
Prime numbers Jordi Cortadella Department of Computer Science.
Analysis of Algorithms
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Recursion Jordi Cortadella Department of Computer Science.
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Sequences Jordi Cortadella Department of Computer Science.
Search algorithms for vectors Jordi Cortadella Department of Computer Science.
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Data structure design Jordi Cortadella Department of Computer Science.
Polynomials Jordi Cortadella Department of Computer Science.
CSC 211 Data Structures Lecture 13
First steps Jordi Cortadella Department of Computer Science.
Data Structure Introduction.
For loops, nested loops and scopes Jordi Cortadella Department of Computer Science.
Introduction to Programming (in C++) Sorting Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Introduction to Programming (in C++) Numerical algorithms Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Vectors Jordi Cortadella Department of Computer Science.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Vishnu Kotrajaras, PhD.1 Data Structures
Parameter passing Jordi Cortadella Department of Computer Science.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 3. Introduction to the Analysis of Algorithms.
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
Jordi Cortadella, Ricard Gavaldà, Fernando Orejas
Reasoning with invariants
For loops, nested loops and scopes
CS 213: Data Structures and Algorithms
Announcements Final Exam on August 17th Wednesday at 16:00.
Jordi Cortadella Department of Computer Science
Announcements Final Exam on August 19th Saturday at 16:00.
Announcements Final Exam on December 25th Monday at 16:00.
Search algorithms for vectors
7 Arrays.
Jordi Cortadella and Jordi Petit Department of Computer Science
Jordi Cortadella Department of Computer Science
Chapter 18 Recursion.
Introduction to Programming (in C++) Advanced examples
Presentation transcript:

Introduction to Programming (in C++) Vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Outline Vectors Searching in vectors Introduction to Programming© Dept. CS, UPC2

Vectors A vector is a data structure that groups values of the same type under the same name. Declaration: vector name(n); A vector contains n elements of the same type (n can be any expression). name[i] refers to the i-th element of the vector (i can also be any expression) Note: use #include in the program Introduction to Programming© Dept. CS, UPC3 01n-2n-1 name:

Normalizing a sequence Write a program that normalizes a sequence (i.e. subtracts the minimum value from all the elements in the sequence) The input and output sequences will be preceded by the number of elements in the sequence. Input: Output: The program cannot read the sequence more than once. Introduction to Programming© Dept. CS, UPC4 Input: Output:

Normalizing a sequence // Input: a sequence of numbers preceded by the length of the // sequence (there is at least one element in the sequence) // Output: the normalized input sequence (subtracting the minimum // element from each element in the sequence) int main() { int n; cin >> n; // Store the sequence in a vector vector S(n); for (int i = 0; i > S[i]; // Calculate the minimum value int m = S[0]; for (int i = 1; i < n; ++i) { if (S[i] < m) m = S[i]; } // Write the normalized sequence cout << n; for (int i = 0; i < n; ++i) cout << “ “ << S[i] - m; cout << endl; } Introduction to Programming© Dept. CS, UPC5 Can we do this more efficiently?

Min value of a vector // Pre: A is a non-empty vector // Returns the min value of the vector int minimum(const vector & A) { int n = A.size(); int m = A[0]; // visits A[0] // loop to visit A[1..n-1] for (int i = 1; i < n; ++i) { if (A[i] < m) m = A[i]; } return m; } Introduction to Programming© Dept. CS, UPC6

Vectors Vectors introduce some issues that must be taken into account: – a reference to a vector may not always exist. For example, if i=25 and vector x has 10 elements, then the reference x[i] does not exist. – So far, if x and y are two variables with different names, it can be assumed that they are different and independent objects. The only exception is when the alias effect is produced in the call to a function or procedure. For example: Introduction to Programming© Dept. CS, UPC7 int main() { int n;... S(n,n)... }

Vectors if S is the procedure, then x and y become aliases of the same object (i.e., they represent the same object): void S(int& x, int& y) { x = 4; y = 5; cout << x; // Writes 5... } When using vectors, x[i] and x[j] can be aliases if i and j have the same value. For example: i = 4; j = 3; A[i] = 5; A[j + 1] = 6; cout << A[i]; // Writes 6 Introduction to Programming© Dept. CS, UPC8

Vectors When a variable x has a simple type (e.g. int, char, …), the variable represents the same object during the whole execution of the program. However, when a vector x is used, the reference x[i] may represent different objects along the execution of the program. For example: vector x(5);... x[x[0]] = 1; cout << x[x[0]]; // What does this write? Introduction to Programming© Dept. CS, UPC9

Vectors vector x(5); x[0] = 0; x[1] = 0; x[2] = 0; x[3] = 0; x[4] = 0; x[x[0]] = 1; cout << x[x[0]]; // Writes 0 Introduction to Programming© Dept. CS, UPC10

Constant parameters and variables A call-by-value parameter requires a copy of the parameter from the caller to the callee. It may be inefficient if the parameter is large (e.g. a large vector). Call-by-reference can be more efficient, but the callee may unexpectedly modify the parameter. const parameters can be passed by reference and be protected from any modification. How is the protection guaranteed? – const parameters cannot be written inside the function or passed to another function as a non-const parameter. const can also be applied to variables. Their value cannot change after initialization. Use constant global variables only to declare the constants of the program. Introduction to Programming© Dept. CS, UPC11

Constant parameters and variables const double Pi = ; // Constant variable void g(vector & V) {... V[i] = V[i - 1] + 1; // Allowed (V is not const)... } int f(const vector & A) {... A[i] = A[i - 1] + 1; // Illegal (A is const) g(A); // Illegal (parameter of g is not const) Pi = 3.14; // Illegal (Pi is const)... } Introduction to Programming© Dept. CS, UPC12

Average value of a vector Given a non-empty vector, return the average value of the elements in the vector. Introduction to Programming© Dept. CS, UPC13 // Pre: a non-empty vector A // Returns the average value of the elements in A double average(const vector & A) { int n = A.size(); int sum = 0; for (int i = 0; i < n; ++i) { sum = sum + A[i]; } // Be careful: enforce a “double” result return double(sum)/n; }

Reversing a vector Design a procedure that reverses the contents of a vector: Invariant: Introduction to Programming© Dept. CS, UPC i last-i 0last reversed not reversed

Reversing a vector // Pre: - // Post: A contains the reversed contents // of the input vector void reverse(vector & A) { int last = A.size() - 1; // Calculate the last location to reverse int middle = A.size()/2 - 1; // Reverse one half with the other half for (int i = 0; i <= middle; ++i) { int z = A[i]; A[i] = A[last - i]; A[last - i] = z; } Introduction to Programming© Dept. CS, UPC15

Reversing a vector (another version) // Pre: - // Post: A contains the reversed contents // of the input vector void reverse(vector & A) { int i = 0; int last = A.size() - 1; // Inv: The elements in A[0…i-1] have been // reversed with the elements in // A[last+1…A.size()-1] while (i < last) { int z = A[i]; A[i] = A[last]; A[last] = z; i = i + 1; last = last – 1; } Introduction to Programming© Dept. CS, UPC16

The largest null segment of a vector A null segment is a compact sub-vector in which the sum of all the elements is zero. Let us consider vectors sorted in increasing order. Introduction to Programming© Dept. CS, UPC Null segment Largest null segment

The largest null segment of a vector Observations: – If a null segment contains non-zero elements, then it must contain positive and negative elements. – Let us consider a segment of a vector. If the sum of the elements is positive, then the largest positive value cannot belong to any null segment included in the segment. – The same is true for negative numbers. Introduction to Programming© Dept. CS, UPC18

The largest null segment of a vector Invariant: Introduction to Programming© Dept. CS, UPC The largest null segment is included in the [left…right] segment sum contains the sum of the elements in the [left…right] segment left right sum = 1 Observation: the search will finish when sum = 0. If the segment becomes empty (no elements) the sum will become 0.

The largest null segment of a vector // Pre: A is sorted in increasing order // Post: contain the indices of the // largest null segment. In the case of an empty // null segment, left > right. void largest_null_segment (const vector & A, int& left, int& right) left = 0; right = A.size()-1; int sum = sum_vector(A); // Calculates the sum of A while (sum != 0) { if (sum > 0) { sum = sum – A[right]; right = right – 1; } else { sum = sum – A[left]; left = left + 1; } } // sum = 0 and the largest segment is A[left...right] } Introduction to Programming© Dept. CS, UPC20

typedef Typedef declarations create synonyms for existing types: // Declaration of the type typedef vector listTemperatures; // Declaration of a variable listTemperatures MyTemp; // The parameter of a function double maxTemp(const listTemperatures& L) {... } Introduction to Programming© Dept. CS, UPC21

Polynomial evaluation (Horner’s scheme) Introduction to Programming© Dept. CS, UPC22

Polynomial evaluation (Horner’s scheme) // Definition of a polynomial (the coefficient of degree i // is stored in location i of the vector). typedef vector Polynomial; // Pre: - // Returns the evaluation of P(x) double PolyEval(const Polynomial& P, double x) { double eval = 0; int degree = P.size() - 1; / Invariant: the polynomial has been evaluated up to the coefficient i+1 using Horner’s scheme / for (int i = degree; i >= 0; --i) { eval = evalx + P[i]; } return eval; } Introduction to Programming© Dept. CS, UPC23

SEARCHING IN VECTORS Introduction to Programming© Dept. CS, UPC24

Search in a vector We want to design a function that searches for a value in a vector. The function must return the index of the location in which the value is found. It must return -1 if not found. If several locations contain the search value, it must return the index of one of them. Introduction to Programming© Dept. CS, UPC25 // Pre: A is a non-empty vector // Returns i, such that A[i] == x, if x is in A. // Returns -1 if x is not in A.

Search in a vector Introduction to Programming© Dept. CS, UPC26 Invariant: x does not exist in A[0..i-1]. Note: an interval A[p..q] with p > q is assumed to be an empty interval i

Search in a vector // Pre: -- // Returns i, such that A[i] == x, if x is in A. // Returns -1 if x is not in A. int search(int x, const vector & A) { // Inv: x does not exist in A[0..i-1]. for (int i = 0; i < A.size(); ++i) { if (A[i] == x) return i; } return -1; } Introduction to Programming© Dept. CS, UPC27

Search with sentinel The previous code has a loop with two conditions: – i < A.size(): to detect the end of the vector – A[i] == x: to detect when the value is found The search is more efficient if the first condition is avoided (if we ensure that the value is always in the vector). To enforce this condition, a sentinel may be added in the last (unused) location of the vector. When the sentinel is found, it indicates that the value was not anywhere else in the vector. Introduction to Programming© Dept. CS, UPC28

Search with sentinel // Pre: A is a non-empty vector. The last // element is a non-used location. // Returns i, such that A[i] == x, if x is in A // (without considering the last location). // Returns -1 if x is not in A. int search(int x, vector & A) { int n = A.size(); // The vector has n-1 used elements A[n - 1] = x; // Writes the sentinel int i = 0; // Inv: x does not exist in A[0..i-1] while (A[i] != x) i = i + 1; if (i == n - 1) return -1; else return i; } Introduction to Programming© Dept. CS, UPC29 Be careful: not a const parameter

How would you search in a dictionary? Dictionaries contain a list of sorted words. To find a word in a dictionary of 50,000 words, you would never check the first word, then the second, then the third, etc. Instead, you would look somewhere in the middle and decide if you have to continue forwards or backwards, then you would look again around the middle of the selected part, go forwards/backwards, and so on and so forth … Introduction to Programming© Dept. CS, UPC30

Binary search Introduction to Programming© Dept. CS, UPC Is 4 in the vector? 4 is larger Half of the elements have been discarded ! 4 is smaller Found !

Binary search How many iterations do we need in the worst case? The search will finish when only one element is left: Introduction to Programming© Dept. CS, UPC32 iteration i elements nn/2n/4n/8n/16n/32n/64n/128n/2 i

Binary search Introduction to Programming© Dept. CS, UPC left right Invariant: If x is in vector A, then it will be found in fragment A[left...right] The search will be completed when the value has been found or the interval is empty (left > right)

Binary search // Pre: A is sorted in ascending order, // 0 & A, int left, int right) { while (left A[i]) left = i + 1; else return i; //Found } return -1; } Introduction to Programming© Dept. CS, UPC34

Binary search // The initial call to bin_search should // request a search in the whole array... int i = bin_search(value, A, 0, A.size() – 1);... Introduction to Programming© Dept. CS, UPC35

Binary search (recursive) // Pre: A is sorted in ascending order, // 0 & A, int left, int right) { if (left > right) return -1; else { int i = (left + right)/2; if (x A[i]) return bin_search(x,A,i+1,right); else return i; // found } } Introduction to Programming© Dept. CS, UPC36