Overview. Common tasks. Observation. Chapter 20 The STL (containers, iterators, and algorithms) 8/13/18. Bjarne Stroustrup
|
|
- Meagan Snow
- 5 years ago
- Views:
Transcription
1 Overview Chapter 20 The STL (cotaiers, iterators, ad algorithms) Bjare Stroustrup Commo tasks ad ideals Geeric programmig Cotaiers, algorithms, ad iterators The simplest algorithm: fid() Parameterizatio of algorithms fid_if() ad fuctio objects Sequece cotaiers vector ad list Associative cotaiers map, set Stadard algorithms copy, sort, Iput iterators ad output iterators List of useful facilities Headers, algorithms, cotaiers, fuctio objects Stroustrup/Programmig - Nov'13 3 Commo tasks Observatio Collect data ito cotaiers Orgaize data For pritig For fast access Retrieve data items By idex (e.g., get the th elemet) By value (e.g., get the first elemet with the value "Chocolate") By properties (e.g., get the first elemets where age<64 ) Add data Remove data Sortig ad searchig Simple umeric operatios We ca (already) write programs that are very similar idepedet of the data type used Usig a it is t that differet from usig a double Usig a vector<it> is t that differet from usig a vector<strig> Stroustrup/Programmig - Nov'13 4 Stroustrup/Programmig - Nov'13 5 1
2 Ideals Ideals (cotiued) We d like to write commo programmig tasks so that we do t have to re-do the work each time we fid a ew way of storig the data or a slightly differet way of iterpretig the data Fidig a value i a vector is t all that differet from fidig a value i a list or a array Lookig for a strig igorig case is t all that differet from lookig at a strig ot igorig case Graphig experimetal data with exact values is t all that differet from graphig data with rouded values Copyig a file is t all that differet from copyig a vector Code that s Easy to read Easy to modify Regular Short Fast Uiform access to data Idepedetly of how it is stored Idepedetly of its type Stroustrup/Programmig - Nov'13 6 Stroustrup/Programmig - Nov'13 Ideals (cotiued) Examples Type-safe access to data Easy traversal of data Compact storage of data Fast Retrieval of data Additio of data Deletio of data Stadard versios of the most commo algorithms Copy, fid, search, sort, sum, Stroustrup/Programmig - Nov'13 8 Sort a vector of strigs Fid a umber i a phoe book, give a ame Fid the highest temperature Fid all values larger tha 800 Fid the first occurrece of the value 1 Sort the telemetry records by uit umber Sort the telemetry records by time stamp Fid the first value larger tha Peterse? What is the largest amout see? Fid the first differece betwee two sequeces Compute the pairwise product of the elemets of two sequeces What are the highest temperatures for each day i a moth? What are the top 10 best-sellers? What s the etry for C++ (say, i Google)? What s the sum of the elemets? Stroustrup/Programmig - Nov'13 9 2
3 Geeric programmig Liftig example (cocrete algorithms) Geeralize algorithms Sometimes called liftig a algorithm The aim (for the ed user) is Icreased correctess Through better specificatio Greater rage of uses Possibilities for re-use Better performace Through wider use of tued libraries Uecessarily slow code will evetually be throw away Go from the cocrete to the more abstract The other way most ofte leads to bloat double sum(double array[], it ) // oe cocrete algorithm (doubles i array) double s = 0; for (it i = 0; i < ; ++i ) s += array[i]; retur s; struct Node Node* ext; it data; ; it sum(node* first) it s = 0; while (first) s += first->data; first = first->ext; retur s; // aother cocrete algorithm (its i list) // termiates whe expressio is false or zero Stroustrup/Programmig - Nov'13 10 Stroustrup/Programmig - Nov'13 11 Liftig example (abstract the data structure) Liftig example (STL versio) // pseudo-code for a more geeral versio of both algorithms it sum(data) // somehow parameterize with the data structure it s = 0; // iitialize while (ot at ed) // loop through all elemets s += get value; // compute sum get ext data elemet; retur s; // retur result We eed three operatios (o the data structure): ot at ed get value // Cocrete STL-style code for a more geeral versio of both algorithms template<class Iter, class T> // Iter should be a Iput_iterator // T should be somethig we ca + ad = T sum(iter first, Iter last, T s) // T is the accumulator type while (first!=last) s += *first; ++first; retur s; Let the user iitialize the accumulator float a[] = 1,2,3,4,5,6,,8 ; double d = 0; d = sum(a,a+sizeof(a)/sizeof(*a),d); get ext data elemet Stroustrup/Programmig - Nov'13 12 Stroustrup/Programmig - Nov'
4 Liftig example The STL Almost the stadard library accumulate I simplified a bit for terseess (see 21.5 for more geerality ad more details) Works for arrays vectors lists istreams Rus as fast as had-crafted code Give decet iliig The code s requiremets o its data has become explicit We uderstad the code better Part of the ISO C++ Stadard Library Mostly o-umerical Oly 4 stadard algorithms specifically do computatio accumulate, ier_product, partial_sum, adjacet_differece Hadles textual data as well as umeric data E.g. strig Deals with orgaizatio of code ad data Built-i types, user-defied types, ad data structures Optimizig disk access was amog its origial uses Performace was always a key cocer Stroustrup/Programmig - Nov'13 14 Stroustrup/Programmig - Nov'13 15 The STL Desiged by Alex Stepaov Geeral aim: The most geeral, most efficiet, most flexible represetatio of cocepts (ideas, algorithms) Represet separate cocepts separately i code Combie cocepts freely wherever meaigful Geeral aim to make programmig like math or eve Good programmig is math works for itegers, for floatig-poit umbers, for polyomials, for Algorithms sort, fid, search, copy, Basic model iterators Cotaiers vector, list, map, uordered_map, Separatio of cocers Algorithms maipulate data, but do t kow about cotaiers Cotaiers store data, but do t kow about algorithms Algorithms ad cotaiers iteract through iterators Each cotaier has its ow iterator types Stroustrup/Programmig - Nov'13 16 Stroustrup/Programmig - Nov'13 1 4
5 The STL A ISO C++ stadard framework of about 10 cotaiers ad about 60 algorithms coected by iterators Other orgaizatios provide more cotaiers ad algorithms i the style of the STL Boost.org, Microsoft, SGI, Probably the curretly best kow ad most widely used example of geeric programmig The STL If you kow the basic cocepts ad a few examples you ca use the rest Full documetatio: Google C++ STL More accessible ad less complete documetatio Appedix B Stroustrup/Programmig - Nov'13 18 Stroustrup/Programmig - Nov'13 19 Basic model A pair of iterators defies a sequece The begiig (poits to the first elemet if ay) The ed (poits to the oe-beyod-the-last elemet) vector Cotaiers (hold sequeces i differece ways) begi: ed: list (doubly liked) A iterator is a type that supports the iterator operatios ++ Go to ext elemet * Get value == Does this iterator poit to the same elemet as that iterator? Some iterators support more operatios (e.g. --, +, ad [ ]) Stroustrup/Programmig - Nov'13 20 set (a kid of tree) Stroustrup/Programmig - Nov'
6 begi: The simplest algorithm: fid() // Fid the first elemet that equals a value template<class I, class T> I fid(i first, I last, cost T& val) while (first!=last && *first!= val) ++first; retur first; ed: void f(vector<it>& v, it x) // fid a it i a vector vector<it>::iterator p = fid(v.begi(),v.ed(),x); if (p!=v.ed()) /* we foud x */ We ca igore ( abstract away ) the differeces betwee cotaiers Stroustrup/Programmig - Nov'13 22 fid() geeric for both elemet type ad cotaier type void f(vector<it>& v, it x) // works for vector of its vector<it>::iterator p = fid(v.begi(),v.ed(),x); if (p!=v.ed()) /* we foud x */ void f(list<strig>& v, strig x) // works for list of strigs list<strig>::iterator p = fid(v.begi(),v.ed(),x); if (p!=v.ed()) /* we foud x */ void f(set<double>& v, double x) // works for set of doubles set<double>::iterator p = fid(v.begi(),v.ed(),x); if (p!=v.ed()) /* we foud x */ Stroustrup/Programmig - Nov'13 23 Algorithms ad iterators A iterator poits to (refers to, deotes) a elemet of a sequece The ed of the sequece is oe past the last elemet ot the last elemet That s ecessary to elegatly represet a empty sequece Oe-past-the-last-elemet is t a elemet You ca compare a iterator poitig to it You ca t dereferece it (read its value) Returig the ed of the sequece is the stadard idiom for ot foud or usuccessful A empty sequece: some iterator: the ed: begi: ed: Stroustrup/Programmig - Nov'13 24 Simple algorithm: fid_if() Fid the first elemet that matches a criterio (predicate) Here, a predicate takes oe argumet ad returs a bool template<class I, class Pred> I fid_if(i first, I last, Pred pred) while (first!=last &&!pred(*first)) ++first; retur first; void f(vector<it>& v) vector<it>::iterator p = fid_if(v.begi(),v.ed,odd()); if (p!=v.ed()) /* we foud a odd umber */ Stroustrup/Programmig - Nov'13 A predicate 25 6
7 Predicates A predicate (of oe argumet) is a fuctio or a fuctio object that takes a argumet ad returs a bool For example A fuctio bool odd(it i) retur i%2; // % is the remaider (modulo) operator odd(); // call odd: is odd? A fuctio object struct Odd bool operator()(it i) cost retur i%2; ; Odd odd; // make a object odd of type Odd odd(); // call odd: is odd? Fuctio objects A cocrete example usig state template<class T> struct Less_tha T val; // value to compare with Less_tha(T& x) :val(x) bool operator()(cost T& x) cost retur x < val; ; // fid x<43 i vector<it> : p=fid_if(v.begi(), v.ed(), Less_tha(43)); Stroustrup/Programmig - Nov'13 26 // fid x<"perfectio" i list<strig>: q=fid_if(ls.begi(), ls.ed(), Less_tha("perfectio")); Stroustrup/Programmig - Nov'13 2 Fuctio objects A very efficiet techique iliig very easy ad effective with curret compilers Faster tha equivalet fuctio Ad sometimes you ca t write a equivalet fuctio The mai method of policy parameterizatio i the STL Key to emulatig fuctioal programmig techiques i C++ Policy parameterizatio Wheever you have a useful algorithm, you evetually wat to parameterize it by a policy. For example, we eed to parameterize sort by the compariso criteria struct Record strig ame; char addr[24]; ; // stadard strig for ease of use // old C-style strig to match database layout vector<record> vr; sort(vr.begi(), vr.ed(), Cmp_by_ame()); sort(vr.begi(), vr.ed(), Cmp_by_addr()); // sort by ame // sort by addr Stroustrup/Programmig - Nov'13 28 Stroustrup/Programmig - Nov'13 29
8 Comparisos // Differet comparisos for Rec objects: struct Cmp_by_ame bool operator()(cost Rec& a, cost Rec& b) cost retur a.ame < b.ame; // look at the ame field of Rec ; struct Cmp_by_addr bool operator()(cost Rec& a, cost Rec& b) cost retur 0 < strcmp(a.addr, b.addr, 24); // correct? ; // ote how the compariso fuctio objects are used to hide ugly // ad error-proe code Policy parameterizatio Wheever you have a useful algorithm, you evetually wat to parameterize it by a policy. For example, we eed to parameterize sort by the compariso criteria vector<record> vr; sort(vr.begi(), vr.ed(), [] (cost Rec& a, cost Rec& b) retur a.ame < b.ame; // sort by ame ); sort(vr.begi(), vr.ed(), [] (cost Rec& a, cost Rec& b) retur 0 < strcmp(a.addr, b.addr, 24); // sort by addr ); Stroustrup/Programmig - Nov'13 30 Stroustrup/Programmig - Nov'13 31 Policy parameterizatio Use a amed object as argumet If you wat to do somethig complicated If you feel the eed for a commet If you wat to do the same i several places Use a lambda expressio as argumet If what you wat is short ad obvious Choose based o clarity of code There are o performace differeces betwee fuctio objects ad lambdas Fuctio objects (ad lambdas) ted to be faster tha fuctio argumets vector template<class T> class vector T* elemets; usig value_type = T; usig iterator =???; // the type of a iterator is implemetatio defied // ad it (usefully) varies (e.g. rage checked iterators) // a vector iterator could be a poiter to a elemet usig cost_iterator =???; iterator begi(); cost_iterator begi() cost; iterator ed(); cost_iterator ed() cost; // poits to first elemet // poits to oe beyod the last elemet ; iterator erase(iterator p); // remove elemet poited to by p iterator isert(iterator p, cost T& v); // isert a ew elemet v before p Stroustrup/Programmig - Nov'13 32 Stroustrup/Programmig - Nov'
9 isert() ito vector vector<it>::iterator p = v.begi(); ++p; ++p; ++p; vector<it>::iterator q = p; ++q; p = v.erase(p); erase() from vector // leaves p poitig at the elemet after the erased oe 5 p=v.isert(p,99); // leaves p poitig at the iserted elemet Note: q is ivalid after the isert() Note: Some elemets moved; all elemets could have moved Stroustrup/Programmig - Nov' vector elemets move whe you isert() or erase() Iterators ito a vector are ivalidated by isert() ad erase() Stroustrup/Programmig - Nov'13 35 template<class T> class list Lik* elemets; list usig value_type = T; usig iterator =???; // the type of a iterator is implemetatio defied // ad it (usefully) varies (e.g. rage checked iterators) // a list iterator could be a poiter to a lik ode usig cost_iterator =???; iterator begi(); cost_iterator begi() cost; iterator ed(); cost_iterator ed() cost; // poits to first elemet Lik: // poits oe beyod the last elemet T value Lik* pre Lik* post iterator erase(iterator p); // remove elemet poited to by p iterator isert(iterator p, cost T& v); // isert a ew elemet v before p ; Stroustrup/Programmig - Nov'13 36 isert() ito list list<it>::iterator p = v.begi(); ++p; ++p; ++p; list<it>::iterator q = p; ++q; 6 v = v.isert(p,99); // leaves p poitig at the iserted elemet Note: q is uaffected 99 Note: No elemets moved aroud Stroustrup/Programmig - Nov'13 3 9
10 p = v.erase(p); 6 erase() from list // leaves p poitig at the elemet after the erased oe Ways of traversig a vector for(it i = 0; i<v.size(); ++i) // do somethig with v[i] for(vector<t>::size_type i = 0; i<v.size(); ++i) // do somethig with v[i] for(vector<t>::iterator p = v.begi(); p!=v.ed(); ++p) // do somethig with *p Less paiful: for (auto = v.begi(); p!=v.ed(); ++p) // do somethig with *p // why it? // loger but always correct Note: list elemets do ot move whe you isert() or erase() Stroustrup/Programmig - Nov'13 38 Stroustrup/Programmig - Nov'13 39 Ways of traversig a vector Kow all three ways (iterator, subscript, auto) The subscript style is used i essetially every laguage The iterator style is used i C (poiters oly) ad C++ The iterator style is used for stadard library algorithms The subscript style does t work for lists (i C++ ad i most laguages) Use either way for vectors There are o fudametal advatages of oe style over the other But the iterator style works for all sequeces Prefer size_type over plai it pedatic, but quiets compiler ad prevets rare errors Ways of traversig a vector for(vector<t>::iterator p = v.begi(); p!=v.ed(); ++p) // do somethig with *p for(vector<t>::value_type x : v) // do somethig with x for(auto& x : v) // do somethig with x Rage for Use for the simplest loops Every elemet from begi() to ed() Over oe sequece Whe you do t eed to look at more tha oe elemet at a time Whe you do t eed to kow the positio of a elemet Stroustrup/Programmig - Nov'13 40 Stroustrup/Programmig - Nov'
11 Vector vs. List Some useful stadard headers By default, use a vector You eed a reaso ot to You ca grow a vector (e.g., usig push_back()) You ca isert() ad erase() i a vector Vector elemets are compactly stored ad cotiguous For small vectors of small elemets all operatios are fast compared to lists If you do t wat elemets to move, use a list You ca grow a list (e.g., usig push_back() ad push_frot()) You ca isert() ad erase() i a list List elemets are separately allocated Note that there are more cotaiers, e.g., map uordered_map Stroustrup/Programmig - Nov'13 42 <iostream> I/O streams, cout, ci, <fstream> file streams <algorithm> sort, copy, <umeric> accumulate, ier_product, <fuctioal> fuctio objects <strig> <vector> <map> <uordered_map> hash table <list> <set> Stroustrup/Programmig - Nov'13 43 Next lecture Map, set, ad algorithms Stroustrup/Programmig - Nov'
Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup
Chapter 18 Vectors ad Arrays Bjare Stroustrup Vector revisited How are they implemeted? Poiters ad free store Destructors Iitializatio Copy ad move Arrays Array ad poiter problems Chagig size Templates
More informationAbstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:
Chapter 4 Computatio Bjare Stroustrup www.stroustrup.com/programmig Abstract Today, I ll preset the basics of computatio. I particular, we ll discuss expressios, how to iterate over a series of values
More informationn Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.
Bjare Stroustrup www.stroustrup.com/programmig Chapter 5 Errors Abstract Whe we program, we have to deal with errors. Our most basic aim is correctess, but we must deal with icomplete problem specificatios,
More informationHash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.
Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 2015 Hash Tables xkcd. http://xkcd.com/221/. Radom Number. Used with permissio uder Creative
More informationChapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 1 Itroductio to Computers ad C++ Programmig Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 1.1 Computer Systems 1.2 Programmig ad Problem Solvig 1.3 Itroductio to C++ 1.4 Testig
More informationCS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1
CS200: Hash Tables Prichard Ch. 13.2 CS200 - Hash Tables 1 Table Implemetatios: average cases Search Add Remove Sorted array-based Usorted array-based Balaced Search Trees O(log ) O() O() O() O(1) O()
More informationn Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis
Overview Chapter 6 Writig a Program Bjare Stroustrup Some thoughts o software developmet The idea of a calculator Usig a grammar Expressio evaluatio Program orgaizatio www.stroustrup.com/programmig 3 Buildig
More informationChapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 9 Poiters ad Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 9.1 Poiters 9.2 Dyamic Arrays Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Slide 9-3
More informationCS 11 C track: lecture 1
CS 11 C track: lecture 1 Prelimiaries Need a CMS cluster accout http://acctreq.cms.caltech.edu/cgi-bi/request.cgi Need to kow UNIX IMSS tutorial liked from track home page Track home page: http://courses.cms.caltech.edu/courses/cs11/material
More informationChapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Strigs ad Vectors Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Slide 8-3 8.1 A Array Type for Strigs A Array Type for Strigs C-strigs ca be used to represet strigs
More informationComputers and Scientific Thinking
Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput
More informationChapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 11 Frieds, Overloaded Operators, ad Arrays i Classes Copyright 2014 Pearso Addiso-Wesley. All rights reserved. Overview 11.1 Fried Fuctios 11.2 Overloadig Operators 11.3 Arrays ad Classes 11.4
More informationChapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 8 Strigs ad Vectors Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 8.1 A Array Type for Strigs 8.2 The Stadard strig Class 8.3 Vectors Copyright 2015 Pearso Educatio, Ltd..
More informationAnalysis of Algorithms
Aalysis of Algorithms Ruig Time of a algorithm Ruig Time Upper Bouds Lower Bouds Examples Mathematical facts Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite
More informationExamples and Applications of Binary Search
Toy Gog ITEE Uiersity of Queeslad I the secod lecture last week we studied the biary search algorithm that soles the problem of determiig if a particular alue appears i a sorted list of iteger or ot. We
More information. Written in factored form it is easy to see that the roots are 2, 2, i,
CMPS A Itroductio to Programmig Programmig Assigmet 4 I this assigmet you will write a java program that determies the real roots of a polyomial that lie withi a specified rage. Recall that the roots (or
More informationLecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming
Lecture Notes 6 Itroductio to algorithm aalysis CSS 501 Data Structures ad Object-Orieted Programmig Readig for this lecture: Carrao, Chapter 10 To be covered i this lecture: Itroductio to algorithm aalysis
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 6 Defiig Fuctios Pytho Programmig, 2/e 1 Objectives To uderstad why programmers divide programs up ito sets of cooperatig fuctios. To be able to
More informationCopyright 2016 Ramez Elmasri and Shamkant B. Navathe
Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe CHAPTER 18 Strategies for Query Processig Copyright 2016 Ramez Elmasri ad Shamkat B. Navathe Itroductio DBMS techiques to process a query Scaer idetifies
More informationCSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.
CSE Notes 8: Sortig (Last updated //8 7:6 PM) CLRS 7.-7., 9., 8.-8. 8.A. QUICKSORT Cocepts Idea: Take a usorted (sub)array ad partitio ito two subarrays such that p q r x y z x y y z Pivot Customarily,
More informationBasic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.
5-23 The course that gives CM its Zip Memory Maagemet II: Dyamic Storage Allocatio Mar 6, 2000 Topics Segregated lists Buddy system Garbage collectio Mark ad Sweep Copyig eferece coutig Basic allocator
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19
CIS Data Structures ad Algorithms with Java Sprig 09 Stacks, Queues, ad Heaps Moday, February 8 / Tuesday, February 9 Stacks ad Queues Recall the stack ad queue ADTs (abstract data types from lecture.
More informationRecursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames
Uit 4, Part 3 Recursio Computer Sciece S-111 Harvard Uiversity David G. Sulliva, Ph.D. Review: Method Frames Whe you make a method call, the Java rutime sets aside a block of memory kow as the frame of
More informationData Structures and Algorithms Part 1.4
1 Data Structures ad Algorithms Part 1.4 Werer Nutt 2 DSA, Part 1: Itroductio, syllabus, orgaisatio Algorithms Recursio (priciple, trace, factorial, Fiboacci) Sortig (bubble, isertio, selectio) 3 Sortig
More informationChapter 3 Classification of FFT Processor Algorithms
Chapter Classificatio of FFT Processor Algorithms The computatioal complexity of the Discrete Fourier trasform (DFT) is very high. It requires () 2 complex multiplicatios ad () complex additios [5]. As
More informationPolynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0
Polyomial Fuctios ad Models 1 Learig Objectives 1. Idetify polyomial fuctios ad their degree 2. Graph polyomial fuctios usig trasformatios 3. Idetify the real zeros of a polyomial fuctio ad their multiplicity
More informationStructuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software
Structurig Redudacy for Fault Tolerace CSE 598D: Fault Tolerat Software What do we wat to achieve? Versios Damage Assessmet Versio 1 Error Detectio Iputs Versio 2 Voter Outputs State Restoratio Cotiued
More informationCOSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1
COSC 1P03 Ch 7 Recursio Itroductio to Data Structures 8.1 COSC 1P03 Recursio Recursio I Mathematics factorial Fiboacci umbers defie ifiite set with fiite defiitio I Computer Sciece sytax rules fiite defiitio,
More informationWhat are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs
What are we goig to lear? CSC316-003 Data Structures Aalysis of Algorithms Computer Sciece North Carolia State Uiversity Need to say that some algorithms are better tha others Criteria for evaluatio Structure
More informationPseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance
Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Pseudocode ( 1.1) High-level descriptio of a algorithm More structured
More informationRecursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:
Recursio Recursio Jordi Cortadella Departmet of Computer Sciece Priciple: Reduce a complex problem ito a simpler istace of the same problem Recursio Itroductio to Programmig Dept. CS, UPC 2 Mathematical
More information! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.
Liked Lists Uit 5 Sectios 11.9 & 18.1-2 CS 2308 Fall 2018 Jill Seama 11.9: Poiters to Structures! Give the followig Structure: struct Studet { strig ame; // Studet s ame it idnum; // Studet ID umber it
More informationHow do we evaluate algorithms?
F2 Readig referece: chapter 2 + slides Algorithm complexity Big O ad big Ω To calculate ruig time Aalysis of recursive Algorithms Next time: Litterature: slides mostly The first Algorithm desig methods:
More informationAnalysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis
Itro to Algorithm Aalysis Aalysis Metrics Slides. Table of Cotets. Aalysis Metrics 3. Exact Aalysis Rules 4. Simple Summatio 5. Summatio Formulas 6. Order of Magitude 7. Big-O otatio 8. Big-O Theorems
More informationAlgorithm. Counting Sort Analysis of Algorithms
Algorithm Coutig Sort Aalysis of Algorithms Assumptios: records Coutig sort Each record cotais keys ad data All keys are i the rage of 1 to k Space The usorted list is stored i A, the sorted list will
More informationCMPT 125 Assignment 2 Solutions
CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address
More informationAlgorithm Design Techniques. Divide and conquer Problem
Algorithm Desig Techiques Divide ad coquer Problem Divide ad Coquer Algorithms Divide ad Coquer algorithm desig works o the priciple of dividig the give problem ito smaller sub problems which are similar
More informationLecture 5. Counting Sort / Radix Sort
Lecture 5. Coutig Sort / Radix Sort T. H. Corme, C. E. Leiserso ad R. L. Rivest Itroductio to Algorithms, 3rd Editio, MIT Press, 2009 Sugkyukwa Uiversity Hyuseug Choo choo@skku.edu Copyright 2000-2018
More informationMajor CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70
NOTE:. Attempt all seve questios. Major CSL 02 2. Write your ame ad etry o o every sheet of the aswer script. Time 2 Hrs Max Marks 70 Q No Q Q 2 Q 3 Q 4 Q 5 Q 6 Q 7 Total MM 6 2 4 0 8 4 6 70 Q. Write a
More informationECE4050 Data Structures and Algorithms. Lecture 6: Searching
ECE4050 Data Structures ad Algorithms Lecture 6: Searchig 1 Search Give: Distict keys k 1, k 2,, k ad collectio L of records of the form (k 1, I 1 ), (k 2, I 2 ),, (k, I ) where I j is the iformatio associated
More informationAppendix D. Controller Implementation
COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Appedix D Cotroller Implemetatio Cotroller Implemetatios Combiatioal logic (sigle-cycle); Fiite state machie (multi-cycle, pipelied);
More information1/27/12. Vectors: Outline and Reading. Chapter 6: Vectors, Lists and Sequences. The Vector ADT. Applications of Vectors. Array based Vector: Insertion
Chater 6: ectors, Lists ad Sequeces ectors: Outlie ad Readig The ector ADT ( 6.1.1) Array-based imlemetatio ( 6.1.2) Nacy Amato Parasol Lab, Det. CSE, Texas A&M Uiversity Ackowledgemet: These slides are
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 4 Procedural Abstractio ad Fuctios That Retur a Value Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 4.1 Top-Dow Desig 4.2 Predefied Fuctios 4.3 Programmer-Defied Fuctios 4.4
More informationtop() Applications of Stacks
CS22 Algorithms ad Data Structures MW :00 am - 2: pm, MSEC 0 Istructor: Xiao Qi Lecture 6: Stacks ad Queues Aoucemets Quiz results Homework 2 is available Due o September 29 th, 2004 www.cs.mt.edu~xqicoursescs22
More informationPython Programming: An Introduction to Computer Science
Pytho Programmig: A Itroductio to Computer Sciece Chapter 1 Computers ad Programs 1 Objectives To uderstad the respective roles of hardware ad software i a computig system. To lear what computer scietists
More informationCS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016
CS 111: Program Desig I Lecture 15: Objects, Padas, Modules Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago October 13, 2016 OBJECTS AND DOT NOTATION Objects (Implicit i Chapter 2, Variables,
More information1.2 Binomial Coefficients and Subsets
1.2. BINOMIAL COEFFICIENTS AND SUBSETS 13 1.2 Biomial Coefficiets ad Subsets 1.2-1 The loop below is part of a program to determie the umber of triagles formed by poits i the plae. for i =1 to for j =
More informationCIS 121. Introduction to Trees
CIS 121 Itroductio to Trees 1 Tree ADT Tree defiitio q A tree is a set of odes which may be empty q If ot empty, the there is a distiguished ode r, called root ad zero or more o-empty subtrees T 1, T 2,
More informationCIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13
CIS Data Structures ad Algorithms with Java Sprig 08 Stacks ad Queues Moday, February / Tuesday, February Learig Goals Durig this lab, you will: Review stacks ad queues. Lear amortized ruig time aalysis
More informationn We have discussed classes in previous lectures n Here, we discuss design of classes n Library design considerations
Chapter 14 Graph class desig Bjare Stroustrup Abstract We have discussed classes i previous lectures Here, we discuss desig of classes Library desig cosideratios Class hierarchies (object-orieted programmig)
More informationNTH, GEOMETRIC, AND TELESCOPING TEST
NTH, GEOMETRIC, AND TELESCOPING TEST Sectio 9. Calculus BC AP/Dual, Revised 08 viet.dag@humbleisd.et /4/08 0:0 PM 9.: th, Geometric, ad Telescopig Test SUMMARY OF TESTS FOR SERIES Lookig at the first few
More informationSolution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:
CS 604 Data Structures Midterm Sprig, 00 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Istructios: Prit your ame i the space provided below. This examiatio is closed book ad closed
More informationCSE 417: Algorithms and Computational Complexity
Time CSE 47: Algorithms ad Computatioal Readig assigmet Read Chapter of The ALGORITHM Desig Maual Aalysis & Sortig Autum 00 Paul Beame aalysis Problem size Worst-case complexity: max # steps algorithm
More informationCode Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013
Code Review s Authors: Mika V. Mätylä ad Casper Lasseius Origial versio: 4 Sep, 2007 Made available olie: 24 April, 2013 This documet cotais further details of the code review defects preseted i [1]. of
More informationCSC 220: Computer Organization Unit 11 Basic Computer Organization and Design
College of Computer ad Iformatio Scieces Departmet of Computer Sciece CSC 220: Computer Orgaizatio Uit 11 Basic Computer Orgaizatio ad Desig 1 For the rest of the semester, we ll focus o computer architecture:
More informationn The C++ template facility provides the ability to define n A generic facility allows code to be written once then
UCLA PIC 10 B Problem Solvig usig C++ Programmig Ivo Diov, Asst. Prof. i Mathematics, Neurology, Statistics Istructor: Teachig Assistat: Suzae Nezzar, Mathematics Chapter 13 Templates for More Abstractio
More informationChapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 10 Defiig Classes Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types 10.4 Itroductio to Iheritace Copyright 2015 Pearso Educatio,
More informationChapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 2 C++ Basics Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 2.1 Variables ad Assigmets 2.2 Iput ad Output 2.3 Data Types ad Expressios 2.4 Simple Flow of Cotrol 2.5 Program
More informationMorgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5
Morga Kaufma Publishers 26 February, 28 COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Chapter 5 Set-Associative Cache Architecture Performace Summary Whe CPU performace icreases:
More informationLecture 1: Introduction and Strassen s Algorithm
5-750: Graduate Algorithms Jauary 7, 08 Lecture : Itroductio ad Strasse s Algorithm Lecturer: Gary Miller Scribe: Robert Parker Itroductio Machie models I this class, we will primarily use the Radom Access
More informationClasses and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1
Classes ad Objects jvo@ualg.pt José Valete de Oliveira 4-1 Agai: Distace betwee poits withi the first quadrat Sample iput Sample output 1 1 3 4 2 jvo@ualg.pt José Valete de Oliveira 4-2 1 The simplest
More informationChapter 24. Sorting. Objectives. 1. To study and analyze time efficiency of various sorting algorithms
Chapter 4 Sortig 1 Objectives 1. o study ad aalyze time efficiecy of various sortig algorithms 4. 4.7.. o desig, implemet, ad aalyze bubble sort 4.. 3. o desig, implemet, ad aalyze merge sort 4.3. 4. o
More informationwhy study sorting? Sorting is a classic subject in computer science. There are three reasons for studying sorting algorithms.
Chapter 5 Sortig IST311 - CIS65/506 Clevelad State Uiversity Prof. Victor Matos Adapted from: Itroductio to Java Programmig: Comprehesive Versio, Eighth Editio by Y. Daiel Liag why study sortig? Sortig
More informationCIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)
CIS 11 Data Structures ad Algorithms with Java Fall 017 Big-Oh Notatio Tuesday, September 5 (Make-up Friday, September 8) Learig Goals Review Big-Oh ad lear big/small omega/theta otatios Practice solvig
More informationHomework 1 Solutions MA 522 Fall 2017
Homework 1 Solutios MA 5 Fall 017 1. Cosider the searchig problem: Iput A sequece of umbers A = [a 1,..., a ] ad a value v. Output A idex i such that v = A[i] or the special value NIL if v does ot appear
More informationSorting in Linear Time. Data Structures and Algorithms Andrei Bulatov
Sortig i Liear Time Data Structures ad Algorithms Adrei Bulatov Algorithms Sortig i Liear Time 7-2 Compariso Sorts The oly test that all the algorithms we have cosidered so far is compariso The oly iformatio
More informationData Structures Week #5. Trees (Ağaçlar)
Data Structures Week #5 Trees Ağaçlar) Trees Ağaçlar) Toros Gökarı Avrupa Gökarı October 28, 2014 Boraha Tümer, Ph.D. 2 Trees Ağaçlar) October 28, 2014 Boraha Tümer, Ph.D. 3 Outlie Trees Deiitios Implemetatio
More informationHeaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015
Presetatio for use with the textbook Algorithm Desig ad Applicatios, by M. T. Goodrich ad R. Tamassia, Wiley, 201 Heaps 201 Goodrich ad Tamassia xkcd. http://xkcd.com/83/. Tree. Used with permissio uder
More informationCOP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen
COP4020 Programmig Laguages Subrouties ad Parameter Passig Prof. Robert va Egele Overview Parameter passig modes Subroutie closures as parameters Special-purpose parameters Fuctio returs COP4020 Fall 2016
More informationLinked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes
Prelimiaries Liked Lists public class StrageObject { Strig ame; StrageObject other; Arrays are ot always the optimal data structure: A array has fixed size eeds to be copied to expad its capacity Addig
More informationCS 111: Program Design I Lecture 21: Network Analysis. Robert H. Sloan & Richard Warner University of Illinois at Chicago April 10, 2018
CS 111: Program Desig I Lecture 21: Network Aalysis Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago April 10, 2018 NETWORK ANALYSIS Which displays a graph i the sese of graph/etwork aalysis?
More informationThe Magma Database file formats
The Magma Database file formats Adrew Gaylard, Bret Pikey, ad Mart-Mari Breedt Johaesburg, South Africa 15th May 2006 1 Summary Magma is a ope-source object database created by Chris Muller, of Kasas City,
More informationChapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.
Chapter 5 Fuctios for All Subtasks Copyright 2015 Pearso Educatio, Ltd.. All rights reserved. Overview 5.1 void Fuctios 5.2 Call-By-Referece Parameters 5.3 Usig Procedural Abstractio 5.4 Testig ad Debuggig
More informationCHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs
CHAPTER IV: GRAPH THEORY Sectio : Itroductio to Graphs Sice this class is called Number-Theoretic ad Discrete Structures, it would be a crime to oly focus o umber theory regardless how woderful those topics
More informationFrom last week. Lecture 5. Outline. Principles of programming languages
Priciples of programmig laguages From last week Lecture 5 http://few.vu.l/~silvis/ppl/2007 Natalia Silvis-Cividjia e-mail: silvis@few.vu.l ML has o assigmet. Explai how to access a old bidig? Is & for
More informationGreedy Algorithms. Interval Scheduling. Greedy Algorithms. Interval scheduling. Greedy Algorithms. Interval Scheduling
Greedy Algorithms Greedy Algorithms Witer Paul Beame Hard to defie exactly but ca give geeral properties Solutio is built i small steps Decisios o how to build the solutio are made to maximize some criterio
More informationLower Bounds for Sorting
Liear Sortig Topics Covered: Lower Bouds for Sortig Coutig Sort Radix Sort Bucket Sort Lower Bouds for Sortig Compariso vs. o-compariso sortig Decisio tree model Worst case lower boud Compariso Sortig
More informationArray Applications. Sorting. Want to put the contents of an array in order. Selection Sort Bubble Sort Insertion Sort. Quicksort Quickersort
Sortig Wat to put the cotets of a arra i order Selectio Sort Bubble Sort Isertio Sort Quicksort Quickersort 2 tj Bubble Sort - coceptual Sort a arra of umbers ito ascedig or descedig order Split the list
More informationRunning Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments
Ruig Time Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects. The
More informationData Structures and Algorithms. Analysis of Algorithms
Data Structures ad Algorithms Aalysis of Algorithms Outlie Ruig time Pseudo-code Big-oh otatio Big-theta otatio Big-omega otatio Asymptotic algorithm aalysis Aalysis of Algorithms Iput Algorithm Output
More informationBig-O Analysis. Asymptotics
Big-O Aalysis 1 Defiitio: Suppose that f() ad g() are oegative fuctios of. The we say that f() is O(g()) provided that there are costats C > 0 ad N > 0 such that for all > N, f() Cg(). Big-O expresses
More informationOnes Assignment Method for Solving Traveling Salesman Problem
Joural of mathematics ad computer sciece 0 (0), 58-65 Oes Assigmet Method for Solvig Travelig Salesma Problem Hadi Basirzadeh Departmet of Mathematics, Shahid Chamra Uiversity, Ahvaz, Ira Article history:
More informationLecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions
U.C. Berkeley CS170 : Algorithms Midterm 1 Solutios Lecturers: Sajam Garg ad Prasad Raghavedra Feb 1, 017 Midterm 1 Solutios 1. (4 poits) For the directed graph below, fid all the strogly coected compoets
More informationSD vs. SD + One of the most important uses of sample statistics is to estimate the corresponding population parameters.
SD vs. SD + Oe of the most importat uses of sample statistics is to estimate the correspodig populatio parameters. The mea of a represetative sample is a good estimate of the mea of the populatio that
More informationOperating System Concepts. Operating System Concepts
Chapter 4: Mass-Storage Systems Logical Disk Structure Logical Disk Structure Disk Schedulig Disk Maagemet RAID Structure Disk drives are addressed as large -dimesioal arrays of logical blocks, where the
More informationRunning Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments
Ruig Time ( 3.1) Aalysis of Algorithms Iput Algorithm Output A algorithm is a step- by- step procedure for solvig a problem i a fiite amout of time. Most algorithms trasform iput objects ito output objects.
More informationAnalysis of Algorithms
Aalysis of Algorithms Iput Algorithm Output A algorithm is a step-by-step procedure for solvig a problem i a fiite amout of time. Ruig Time Most algorithms trasform iput objects ito output objects. The
More informationCSE 111 Bio: Program Design I Lecture 17: software development, list methods
CSE 111 Bio: Program Desig I Lecture 17: software developmet, list methods Robert H. Sloa(CS) & Rachel Poretsky(Bio) Uiversity of Illiois, Chicago October 19, 2017 NESTED LOOPS: REVIEW Geerate times table
More informationCS 111: Program Design I Lecture 15: Modules, Pandas again. Robert H. Sloan & Richard Warner University of Illinois at Chicago March 8, 2018
CS 111: Program Desig I Lecture 15: Modules, Padas agai Robert H. Sloa & Richard Warer Uiversity of Illiois at Chicago March 8, 2018 PYTHON STANDARD LIBRARY & BEYOND: MODULES Extedig Pytho Every moder
More informationCOMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 4. The Processor. Part A Datapath Design
COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Iterface 5 th Editio Chapter The Processor Part A path Desig Itroductio CPU performace factors Istructio cout Determied by ISA ad compiler. CPI ad
More informationCS211 Fall 2003 Prelim 2 Solutions and Grading Guide
CS11 Fall 003 Prelim Solutios ad Gradig Guide Problem 1: (a) obj = obj1; ILLEGAL because type of referece must always be a supertype of type of object (b) obj3 = obj1; ILLEGAL because type of referece
More informationA graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))
ca see that time required to search/sort grows with size of We How do space/time eeds of program grow with iput size? iput. time: cout umber of operatios as fuctio of iput Executio size operatio Assigmet:
More informationSpeeding-up dynamic programming in sequence alignment
Departmet of Computer Sciece Aarhus Uiversity Demark Speedig-up dyamic programmig i sequece aligmet Master s Thesis Dug My Hoa - 443 December, Supervisor: Christia Nørgaard Storm Pederse Implemetatio code
More informationExercise 6 (Week 42) For the foreign students only.
These are the last exercises of the course. Please, remember that to pass exercises, the sum of the poits gathered by solvig the questios ad attedig the exercise groups must be at least 4% ( poits) of
More informationArithmetic Sequences
. Arithmetic Sequeces COMMON CORE Learig Stadards HSF-IF.A. HSF-BF.A.1a HSF-BF.A. HSF-LE.A. Essetial Questio How ca you use a arithmetic sequece to describe a patter? A arithmetic sequece is a ordered
More informationOne advantage that SONAR has over any other music-sequencing product I ve worked
*gajedra* D:/Thomso_Learig_Projects/Garrigus_163132/z_productio/z_3B2_3D_files/Garrigus_163132_ch17.3d, 14/11/08/16:26:39, 16:26, page: 647 17 CAL 101 Oe advatage that SONAR has over ay other music-sequecig
More informationUniversity of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures
Uiversity of Waterloo Departmet of Electrical ad Computer Egieerig ECE 250 Algorithms ad Data Structures Midterm Examiatio ( pages) Istructor: Douglas Harder February 7, 2004 7:30-9:00 Name (last, first)
More informationWORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:
Worked Example 7.1 Producig a Mass Mailig 1 WORKED EXAMPLE 7.1 Producig a Mass Mailig We wat to automate the process of producig mass mailigs. A typical letter might look as follows: To: Ms. Sally Smith
More informationOutline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis
Outlie ad Readig Aalysis of Algorithms Iput Algorithm Output Ruig time ( 3.) Pseudo-code ( 3.2) Coutig primitive operatios ( 3.3-3.) Asymptotic otatio ( 3.6) Asymptotic aalysis ( 3.7) Case study Aalysis
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programmig Laguages Fuctioal Programmig Prof. Robert va Egele Overview What is fuctioal programmig? Historical origis of fuctioal programmig Fuctioal programmig today Cocepts of fuctioal programmig
More information