CSS 342 Data Structures, Algorithms, and Discrete Mathematics I

Slides:



Advertisements
Similar presentations
Chapter 4 ADT Sorted List.
Advertisements

Programming with Recursion
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CARRANO CH ; CUSACK CH 8: OPTIONAL.
 200 Total Points ◦ 74 Points Writing Programs ◦ 60 Points Tracing Algorithms and determining results ◦ 36 Points Short Answer ◦ 30 Points Multiple Choice.
1 MT258 Computer Programming and Problem Solving Unit 7.
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 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
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.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
Pointers OVERVIEW.
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE C++ INTERLUDE 1.3. C++ BOOK.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH 2, APPENDIX E.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1 CSC 222: Computer Programming II Spring 2004 Pointers and dynamic memory  pointer type  dereference operator (*), address-of operator (&)  sorting.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO , APP D, C++ BOOK.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO C++ INTERLUDE 2, CHAPT 4, 6.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
Function Parameters and Overloading Version 1.0. Topics Call-by-value Call-by-reference Call-by-address Constant parameters Function overloading Default.
Searching Arrays Linear search Binary search small arrays
Recursion Powerful Tool
Programming with Recursion
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 19: Recursion.
Sort & Search Algorithms
Recursion.
Stacks.
Topic 6 Recursion.
Template Classes and Functions
Recursion Chapter 12.
Homework 4 questions???.
Chapter 4 Linked Lists.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Programming with Recursion
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
What remains Topics Assignments Final exam
Announcements Final Exam on August 17th Wednesday at 16:00.
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CS 2308 Final Exam Review.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Pointers & Functions.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
C++ Plus Data Structures
Chapter 16 Linked Structures
Array-Based Implementations
Pointers & Dynamic Data Structures
Chapter 18 Recursion.
Pointers & Functions.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Recursion.
CS 2308 Final Exam Review.
Presentation transcript:

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 5. 161013. Carrano Ch 2, Appendix E.

Agenda Lab2 I How to prepare for Quiz Finish Templatizing Website Collateral Quiz Next Thursday! Finish Templatizing Bubble Sort Insertion Sort Program 1 Example Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion.. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion. Recursion Lecture .

How to Study Do problems Review Slides Understand Program 1 Read Books Practice Quiz (on line) Study Groups Review Slides Understand Program 1 Read Books Start from end and work backwards

Quiz Topics Constructors Object Lifetime Templates Vectors, Strings C++ core tenets Class Design ADT C++ Language Coding Guidelines Operator Overloading pass by const, const &, value References Recursion -- TBD Stack v. Heap allocations -- TBD Constructors Object Lifetime Templates Vectors, Strings Sorting: Bubble, Insertion C++ program lifecycle: preprocess, compiler, etc binary, octal, hex -- TBD

In Class Pop Quiz Write a function which takes in a string and reverses the string in-place but returns the original string

Templatize Class SORTED LIST

SortedList Class Template Example Example to show templates on a class which keeps a sorted set of items Add an item Print out items Sort Bonus Points: concatenate two lists Data Structure: Vector Sorts BubbleSort Insertion sort algorithm

#ifndef SORTED_LIST_H #define SORTED_LIST_H #include <iostream> #include <vector> using namespace std; template <class ItemType> class SortedList { public: SortedList(); ~SortedList(); void Add(const ItemType &item); void Print() const; void Sort(); private: vector<ItemType> thelist; }; #include "SortedList.cpp" #endif #ifndef SORTED_LIST_CPP #define SORTED_LIST_CPP #include "SortedList.h" template<class ItemType> SortedList<ItemType>::SortedList(){ } void SortedList<ItemType>::Add(const ItemType &item) { thelist.push_back(item); return; } void SortedList<ItemType>::Print() const for (int i = 0; i < thelist.size(); i++) cout << thelist[i] << endl; #endif

Bubblesort or Sinking Sort Used to sort an array of items by traversing (n-1) times and bubbling largest current item to the bottom Graphical Representation : http://en.wikipedia.org/wiki/Bubble_sort#mediaviewer/File:Bubble-sort- example-300px.gif Bad memory and speed characteristics. “the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems“, Donald Knuth

Insertion Sort Sorted Unsorted Copy 10 Shift 29 Insert 10, copy 14 37 13 Copy 10 Shift 29 29 29 14 37 13 10 29 14 37 13 Insert 10, copy 14 unsortedTop 10 29 29 37 13 Shift 29 10 14 29 37 13 Insert 14; copy 37 10 14 29 37 13 Shift nothing 10 14 29 37 13 Insert 37; Copy 13 10 14 14 29 37 Shift 37, 29 and 14. 10 13 14 29 37 Insert 13 Or Carranno 311-313, Or: http://en.wikipedia.org/wiki/Insertion_sort#mediaviewer/File:Insertion-sort-example-300px.gif

Function for Insertion Sort template<class ItemType> void SortedList<ItemType>::Sort() { for (int place = 1; place < thelist.size(); place++) ItemType temp = thelist[place]; int i = place; while ((i > 0) && (thelist[i-1] > temp)) thelist[i] = thelist[i-1]; i--; } thelist[i] = temp;

VendingBank.h (pt 1) class VendingBank { public: //constructors VendingBank(int id); VendingBank(int id, int pennies, int nickels, int dimes, int quarters, int halves); VendingBank(int id, int amount); // getters - setters int getPennies() const; int getNickels() const; int getDimes() const; int getQuarters() const; int getHalves() const; int getId() const; void setPennies(const int &num); void setNickels(const int &num); void setDimes(const int &num); void setQuarters(const int &num); void setHalves(const int &num); void setId(const int &id);

VendingBank.h (pt 2) //actions bool AddCoins(int pennies, int nickels, int dimes, int quarters, int halves); bool RemoveCoins(int pennies, int nickels, int dimes, int quarters, int halves); bool CanMakeChange(int amount) const; bool isEmpty() const; //operator overloads bool operator==(const VendingBank &) const; bool operator!=(const VendingBank &) const; VendingBank operator+(const VendingBank &) const; VendingBank& operator+=(const VendingBank &); ~VendingBank(); private: int pennies; int nickels; int dimes; int quarters; int halves; int id; Coins makeChange(int amount); };

Recursion Recursion

In order to understand recursion, it helps to understand recursion

In order to understand recursion, it helps to understand recursion

Recursive Solutions Recursion breaks a problem into smaller identical problems Some recursive solutions are inefficient, impractical Complex problems can have simple recursive solutions

Recursive Solutions

Recursive Solutions A recursive solution calls itself Each recursive call solves an identical, smaller problem Test for base case enables recursive calls to stop Eventually one of smaller calls will be base case Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

Compute n! recursively Base Case: n=1 Recursive: n! = n * (n-1) CODE int Factorial(int n) { if (n < 0) return 0; } else if (n == 0) return 1; else return Factorial(n - 1) * n;

FIGURE 2-5 Box trace of fact(3) The Box Trace FIGURE 2-5 Box trace of fact(3) Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

FIGURE 2-5 Box trace of fact(3) … continued The Box Trace FIGURE 2-5 Box trace of fact(3) … continued Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

FIGURE 2-5 Box trace of fact(3) … continued The Box Trace FIGURE 2-5 Box trace of fact(3) … continued Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

The Stack (and recursion) Location in process which stores temp variables, call stack frames, One per thread of execution Heap Location in process which stores dynamically allocated memory (coming soon) Recursion Each call to a function creates stack frame Frame holds temp variables and locals Data in the BOX of the BOX trace Deep Recursion can allocate lots of space on the stack

Recursive example Quiz: Code in class. The maximum number of leaves in a tree can be expressed by the following formula: 𝑓 1, 𝑏 =1 𝑓 ℎ, 𝑏 =𝑏∗𝑓(ℎ−1, 𝑏)   h = height of the tree b = max number of branches per node. Write a recursive function which computes 𝑓 ℎ, 𝑏 .

Class Bell

Time of Invocation (constructors) Automatic Local Each time block is executed Static Local Once –first time it is hit Global In order of declaration in translation unit Typically before main() is entered Destroyed in reverse order of construction Dynamic (tbd) malloc/free new/delete

Printing Numbers in Any Base How to convert a decimal to a hexadecimal Dividend Remainder 16) 123456790(10)……..… 16) 7716049(10)………6 16) 482253(10)………1 16) 30140(10)…13(D) 16) 1883(10)…12(C) 16) 117(10)…11(B) 16) 7(10)……....5 16) 0(10)……....7 1. Divide by a base(16) 2. Print each remainder from the bottom: 75BCD16(16)

Quick review of base conversions 1001012 = 32 + 4 + 1 = 37 more on board…

Printing Numbers in Any Base How to convert a decimal to a hexadecimal Dividend Remainder 16) 123456790(10)……..… 16) 7716049(10)………6 16) 482253(10)………1 16) 30140(10)…13(D) 16) 1883(10)…12(C) 16) 117(10)…11(B) 16) 7(10)……....5 16) 0(10)……....7 1. Divide by a base(16) 2. Print each reminder from the bottom: 75BCD16(16)

Printing numbers in any base (recursively) Base Case: if (num < base) { print out num } Recursive: Pre-pend to the answer ( num % base ) Recursively call with num/base

Printing numbers in any base (recursively) bool PrintBase(int num, int base, string &ans) { string static DIGIT_ARRAY = "0123456789ABCDEF"; if ((num < 0) || (base <= 0) || (base > 16)) return false; } if (num < base) ans = DIGIT_ARRAY[num] + ans; return true; else ans = DIGIT_ARRAY[num % base] + ans; PrintBase(num / base, base, ans);

Recursion w/Alice https://www.youtube.com/watch?v=-3Mcu7o1YSg

Binary Search An entire sorted list First half Second half First half Find a value in an array.

Binary Search Base Case: low or high index finds number Recursive: Determine midpoint (high+low)/2 Search either lower or upper array

Binary Search int BinarySearch(int value, int arr[], int index1, int index2) { if (value == arr[index1]) return index1; else if (value == arr[index2]) return index2; else if (index2 <= index1 + 1) return -1; else int midpoint = (index1 + index2) / 2; if (arr[midpoint] > value) return BinarySearch(value, arr, index1, midpoint); return BinarySearch(value, arr, midpoint, index2); }

What does the box trace look like for binary search?

C++ Fundamentals

Pointers 4 3 1 5 Pointer variables int *p, *q; Static allocation int x; Address-of operator p = &x; Memory cell to which P points *p = 6; Pointer operations q = p; 4 3 1 ? p q x ? p q x ? 6 p q x 5 6 p q x

Arrays Arrays: reservation and construction of indexed set of objects or built-in types int x=5; int arr1[100] int arr2[3] = {34, 7, 34}; char cArr1[7]; char cArr2[10][5]; arr1[x] = 32; arr2[0] = arr1[x]; cArr2[3][3] = ‘a’; Arrays v Pointers (following are equivalent) void Foo(int arr[]) { } void Foo(int *arr) { } MyFooClass theFooObj; MyFooClass arrFoo[200]; //default constructors run MyFooClass *pFoo; pFoo = arrFoo; arrFoo[54] = theFooObj; pFoo = &theFooObj;