CS 46B: Introduction to Data Structures June 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
Back to Sorting – More efficient sorting algorithms.
Chapter 18 Recursion "To iterate is human, to recurse divine.", L. Peter Deutsch.
CMPS1371 Introduction to Computing for Engineers SORTING.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Program Design and Development
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 8 Arrays and Strings
CS 153: Concepts of Compiler Design August 25 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Midterm Test Overview CS221 – 3/23/09. Test Curve Current median is a 71 or C- Median will be adjusted to an 81 or B- All test scores will be +10 on.
CS 146: Data Structures and Algorithms July 14 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 14 – Sorting and Searching.
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Recursive Methods Noter ch.2. QUIZ What is the result of the method call foo(4) ? 1.Prints 4 2.Prints 1 3.Prints Prints Compiler error:
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Copyright © 2013 by John Wiley & Sons. All rights reserved. SORTING AND SEARCHING CHAPTER Slides by Rick Giles 14.
CS 46B: Introduction to Data Structures June 25 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CS 146: Data Structures and Algorithms June 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 8 Arrays and Strings
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sorting and Searching.
Analyzing Complexity of Lists OperationSorted Array Sorted Linked List Unsorted Array Unsorted Linked List Search( L, x ) O(logn) O( n ) O( n ) Insert(
AP Computer Science Instructor Alabama School of Fine Arts
CS 46B: Introduction to Data Structures June 16 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
CS 46B: Introduction to Data Structures July 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CHAPTER 17 RECURSION. CHAPTER GOALS To learn about the method of recursion To understand the relationship between recursion and iteration To analysis.
Chapter 18 Recursion. Chapter Goals To learn about the method of recursion To understand the relationship between recursion and iteration To analyze problems.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
CS 146: Data Structures and Algorithms July 7 Class Meeting
CS 153: Concepts of Compiler Design September 16 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Mutual Recursion A set of methods calls each other cooperatively and repeatedly Expression is a term, or sum or difference of terms Term is a factor, or.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CS 146: Data Structures and Algorithms July 14 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
CS 146: Data Structures and Algorithms July 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS 46B: Introduction to Data Structures July 2 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CS 153: Concepts of Compiler Design September 30 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
CS 146: Data Structures and Algorithms June 11 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CS 152: Programming Language Paradigms April 7 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak
CS 153: Concepts of Compiler Design October 12 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
CS 46B: Introduction to Data Structures July 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
CS 154 Formal Languages and Computability March 8 Class Meeting Department of Computer Science San Jose State University Spring 2016 Instructor: Ron Mak.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CS 152: Programming Language Paradigms February 12 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Sorting Chapter 14.
Information and Computer Sciences University of Hawaii, Manoa
CS 153: Concepts of Compiler Design September 14 Class Meeting
Bubble Sort Bubble sort is one way to sort an array of numbers. Adjacent values are swapped until the array is completely sorted. This algorithm gets its.
Algorithm design and Analysis
CMPE 152: Compiler Design September 13 Class Meeting
14 SORTING AND SEARCHING CHAPTER
Presentation transcript:

CS 46B: Introduction to Data Structures June 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Quizzes for July 2  Quiz 10 July  Quiz 11 July Special Topic

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 4-Final: A Solution  Aggregations: A Company object aggregates multiple Department objects. Each Department object aggregates one Manager object. Each Employee object aggregates an Address object which is inherited by a Manager or Worker. 3 private ArrayList departments = new ArrayList (); private Manager manager; private Address address;

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 4-Final: A Solution  Each Manager object aggregates multiple Worker objects. 4 private ArrayList workers = new ArrayList ();

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 4-Final: A Solution 5 private void printReport(Company company) {... for (Department dept : company.getDepartments()) { Manager mgr = dept.getManager();... for (Worker wrkr : mgr.getWorkers()) {... }  Starting with the company’s department, loop over the aggregated objects. Print headers. Loop over the departments. Print the manager and address. Loop over each manager’s worker. Print each worker and address.

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 5: Recursive Read File  Base case: An empty file, or at end of file: Stop.  Simpler but similar case: A file that’s one line shorter. Therefore, read a line and make a recursive call to read the rest of the file. 6

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 5: Recursive All Same  Base case: A string of length 0 or 1: Return true.  Simpler but similar case: A string that’s shorter. Compare the first two characters of the string and make a recursive call on the rest of the string. 7

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 5: Recursive Count  Base case: An empty string: Return 0.  Simpler but similar case: A shorter string. Check and count the first character, and add to a recursive call on the rest of the string. 8

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework 5: Recursive Append  Base case: The second list is empty: Return the first list.  Simpler but similar case: The second list is shorter. Remove the first element of the second list.  OR: Remove the last element of the second list. Append the removed element to the end of the result of a recursive call to append the (shorter) second list to the first list. 9

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Mutual Recursion  A set of cooperating methods that call each other recursively.  A calculator for arithmetic expressions. Precedence rules: operators * and / bind more tightly than operators + and -  * and / have higher precedence than + and - Parentheses can group subexpressions  The most deeply nested subexpressions are evaluated first. 10

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Syntax Diagrams 11

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Arithmetic Expressions  An expression is broken down into a sequence of terms, separated by + or -  Each term is broken down into a sequence of factors, separated by * or /  Each factor is either a parenthesized expression or a number.  The syntax trees represent which operations should be carried out first *5 (3+4)*5

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Syntax Trees 13

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Clicker Question June 29 #1  Why do we need both terms and factors in the syntax diagram? a. Factors are combined by multiplicative operators ( * and / ), terms are combined by additive operators ( +, - ). b. Terms are combined by multiplicative operators ( * and / ), factors are combined by additive operators ( +, - ). c. We need both so that multiplication can bind more strongly than addition. d. We need both so that we can have mutual recursion. 14

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Mutually Recursive Methods 15  Consider methods getExpressionValue() getTermValue() getFactorValue()  Method getFactorValue() recursively calls method getExpressionValue()

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Expression 16 public int getExpressionValue() { int value = getTermValue(); boolean done = false; while (!done) { String next = tokenizer.peekToken(); if ("+".equals(next) || "-".equals(next)) { tokenizer.nextToken(); // Discard "+" or "-" int value2 = getTermValue(); if ("+".equals(next)) value = value + value2; else value = value - value2; } else { done = true; } } return value; }

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Term 17 public int getTermValue() { int value = getFactorValue(); boolean done = false; while (!done) { String next = tokenizer.peekToken(); if ("*".equals(next) || "/".equals(next)) { tokenizer.nextToken() ; // Discard "*" or "/" int value2 = getFactorValue(); if ("*".equals(next)) value = value*value2; else value = value/value2; } else { done = true; } } return value; }

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Factor 18 public int getFactorValue() { int value; String next = tokenizer.peekToken(); if ("(".equals(next)) { tokenizer.nextToken(); // Discard "(” value = getExpressionValue(); tokenizer.nextToken(); // Discard ")” } else { value = Integer.parseInt(tokenizer.nextToken()); } return value; }

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Clicker Question June 29 #2  What happens if you try to parse the illegal expression 3+4*)5 ? Specifically, which method throws an exception? a. getExpressionValue() b. getTermValue() c. getFactorValue() d. main() 19

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Syntax Tree of (3 + 4)*5 20

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Trace of (3 + 4)*5  getExpressionValue() calls getTermValue() getTermValue() calls getFactorValue()  getFactorValue() consumes the ( input  getFactorValue() calls getExpressionValue() getExpressionValue() returns eventually with the value of 7, having consumed This is the recursive call.  getFactorValue() consumes the ) input  getFactorValue() returns 7 getTermValue() consumes the inputs * and 5 and returns 35  getExpressionValue() returns 35 21

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Clicker Question June 29 #3  Why does the expression parser use mutual recursion? a. To compute the value of an arithmetic expression more efficiently than with a loop. b. To make * and / bind stronger than + and - c. To handle both operators such as * and / and numbers such as 2 and 3 d. To handle parenthesized expressions, such as 2+3*(4+5) 22

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Break 23

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework #6 Final (No Draft)  Modify Evaluator.java to handle: The % modulo operator, which should bind as tightly (have the same precedence level) as * and /  Example: 19%4 = 3 The ^ power operator, which should bind the most tightly of all the operators (have the highest precedence level).  Example: 2^5 = 32  Tip: Look up Math.pow() 24

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Homework #6 Final, cont’d  Codecheck URL: 8msne7gm8q5xfc266nmdvknb5 8msne7gm8q5xfc266nmdvknb5 Ignore the system error message about the unknown pseudo-comment ARGS  Canvas: Homework 6 Final  Due Monday, July 6 at 11:59 PM 25

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Selection Sort  Find the smallest and swap it with the first element.  Find the next smallest. It is already in the correct place.  Find the next smallest and swap it with first element of unsorted portion.  Repeat.  When the unsorted portion is of length 1, we are done. 26

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Selection Sort Performance  How long does it take the selection sort algorithm to sort an array of n elements? 27 Doubling n increases the sorting time about four times.

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Measure Selection Sort Performance  We want to know how the sorting times increase as the array size n increases.  Actual times, of course, depend on CPU speed.  A CPU-neutral way to measure selection sort performance is not to count milliseconds but to count how many times the array elements are visited. 28

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Count Element Visits  To find the smallest value: visit n elements + 2 visits for the swap  To find the next smallest value: visit ( n - 1) elements + 2 visits for the swap  The last term: visit 2 elements + 2 visits for the swap 29

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Analyze Selection Sort Performance  The number of visits: T(n) = n (n - 1) (n - 2) (1)2 + 2 = 2 + … + (n-1) + n + 2(n-1) = because =  Ignore which is small compared to  Also ignore the which will cancel out when comparing ratios. 30

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Analyze Selection Sort Performance, cont’d  The number of visits is of the order n 2  The number of visits is “order n 2 ”: O ( n 2 )  To convert to big-Oh notation: Locate the fastest-growing term Ignore any constant coefficient  Multiplying the number of elements in an array by 2 multiplies the processing time by 4 31  O(n2) O(n2)

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Big-Oh Isn’t Just for Sorting  Find the largest number in an array Set variable largestSoFar to a[0] : 1 visit Compare largestSoFar with a[1] : 1 visit Compare largestSoFar with a[2] : 1 visit... Compare largestSoFar with a[n-1] : 1 visit  Total: n visits  Finding largest number is O ( n ) 32

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Find the Most Frequent Element  Find the most frequent element.  An algorithm: Count how many times 8 occurs: n visits Count how many times 7 occurs: n visits Repeat for each element. Each count is O ( n ). There are n elements, so O ( n 2 ) for all. Find the largest count: O ( n ) All together: O ( n 2 ) + O ( n ) = O ( n 2 ) 33

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Find the Most Frequent Element, cont’d  Another algorithm? What if we sorted the array first? Then identical values are next to each other. Only one pass to find the most frequent element.  What if we used selection sort to do the sorting? 34

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Merge Sort  Uses recursion to sort.  Divide an array in half.  Recursively sort each half. Sort each half the same way, by dividing it in half. Eventually, a half will contain only one element.  Merge the two sorted halves.  Dramatically faster than selection sort! 35

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Merge Sort, cont’d  Divide the array into two halves and sort each half.  Merge the two sorted halves into a single sorted array. 36

Computer Science Dept. Summer 2015: June 30 CS 46B: Introduction to Data Structures © R. Mak Merge Sort, cont’d 37 public void sort(int a[]) { if (a.length <= 1) return; // base case int first[] = new int[a.length/2]; int second[] = new int[a.length - first.length]; // Copy the first half of a into array first, // the second half of a into array second... sort(first); sort(second); merge(first, second); }