1 Gentle Introduction to Programming Session 4: Arrays, Sorting, Efficiency.

Slides:



Advertisements
Similar presentations
Chapter 7: Arrays In this chapter, you will learn about
Advertisements

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
ITC 240: Web Application Programming
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
1 Gentle Introduction to Programming Session 2: Functions.
1 Gentle Introduction to Programming Session 5: Sorting, Searching, Time- Complexity Analysis, Memory Model, Object Oriented Programming.
1 Data Structures A program solves a problem. A program solves a problem. A solution consists of: A solution consists of:  a way to organize the data.
מבוא מורחב 1 Lecture 3 Material in the textbook Sections to
1 Gentle Introduction to Programming Session 3: Higher Order Functions, Recursion.
1 Gentle Introduction to Programming Session 5: Memory Model, Object Oriented Programming.
1 Gentle Introduction to Programming Session 3: Recursion.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Main Index Contents 11 Main Index Contents Selection Sort Selection SortSelection Sort Selection Sort (3 slides) Selection Sort Alg. Selection Sort Alg.Selection.
Copyright © Cengage Learning. All rights reserved. CHAPTER 11 ANALYSIS OF ALGORITHM EFFICIENCY ANALYSIS OF ALGORITHM EFFICIENCY.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
1 Gentle Introduction to Programming Session 2: Functions.
1 Gentle Introduction to Programming Session 4: Arrays.
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
Data Structures Using C++ 2E Chapter 6 Recursion.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Data Structures Using C++ 2E Chapter 6 Recursion.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementation:
Discrete Mathematics Algorithms. Introduction  An algorithm is a finite set of instructions with the following characteristics:  Precision: steps are.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
Recursion.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Chapter 19 Searching, Sorting and Big O
Chapter 12 Recursion, Complexity, and Searching and Sorting
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
CSC 211 Data Structures Lecture 13
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 9.
Chapter 10 Algorithm Analysis.  Introduction  Generalizing Running Time  Doing a Timing Analysis  Big-Oh Notation  Analyzing Some Simple Programs.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Iteration vs. Recursion If we have time: live demo!!!
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part 3. Time Complexity Calculations.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
CMSC201 Computer Science I for Majors Lecture 20 – Recursion (Continued) Prof. Katherine Gibson Based on slides from UPenn’s CIS 110, and from previous.
Chapter 15 Recursion.
Analysis of Algorithms
Introduction to Search Algorithms
Chapter 15 Recursion.
Algorithm Analysis CSE 2011 Winter September 2018.
CS21b: Structure and Interpretation
Algorithm design and Analysis
Data Structures (CS212D) Week # 2: Arrays.
Material in the textbook Sections to 1.2.1
Programming with Recursion
Presentation transcript:

1 Gentle Introduction to Programming Session 4: Arrays, Sorting, Efficiency

2 Admin. Upcoming Tuesday – practical session in the lab Please fix all your account issues before it and make sure you can write Scala programs in Eclipse

3 Review Review on Functions Higher order functions Recursion Solving big instances using the solution to smaller instances Solving directly the base cases Tower of Hanoi Recursion and efficiency (Fibonacci) Importance of correct base-cases (Odd-Even)

4 Today Home work review Guest lecture by Prof. Benny Chor Recursive vs. Iterative Arrays Sorting, searching and time-complexity analysis Home work

5 Approximating Square Root Given integer x > 0, how to find an approximation of x? Newton was the first to notice that for any positive n, and when x 0 =1, the following series converges to sqrt(n):

6 Algorithm x = 2g = 1 x/g = 2g = ½ (1+ 2) = 1.5 x/g = 4/3g = ½ (3/2 + 4/3) = 17/12 = x/g = 24/17g = ½ (17/ /17) = 577/408 = Algorithm: Make a guess g Improve the guess by averaging g, x/g Keep improving the guess until it is good enough Example: calculate the square root of 2

7 Exercise 1 Write a program that receives from the user: An integer x > 0 A double representing the approximation’s accuracy Calculates an approximation of x within the required accuracy Use the function Math.abs(x) which returns the absolute value of x

8 Solution ApproxSQRT.scala g – x/g תיקון לשנה הבאה !!

9 Exercise 2 Write a function that uses the formula :  2 /6=1/1+1/4+1/9+1/16+…+1/n 2 (where n goes to infinity) in order to approximate . The function should accept an argument n which determines the number of terms in the formula. It should return the approximation of  Write a program that gets an integer n from the user, and approximate  using n terms of the above formula Use a nested function sum, with signature:

10 Solution ApproxPI.scala

11 Exercise 3 Write a function deriv : Input: a function f (Double=>Double), accuracy dx Output: function df (Double=>Double), the derivative of f. df (x) = (f(x+dx) – f(x))/dx Define a few simple functions (linear, square) and calculate their derivative at various points received by command line arguments

12 Usage Example // the function you want to derive def f(x : Double) : Double = x * x // resolution/accuracy/granularity of derivative val dx = /* this is the invokation of the function you are supposed to implement*/ val df = deriv(f,dx) // print the derivative of f(x) at x = 10 println(df(10))

13 Solution Derivative.scala toDouble תיקון לשנה הבאה !!

14 Recursion - Exercise 1 Write a program that receives two non- negative integers and computes their product recursively Hint: Notice that the product a*b is actually a+a+…+a (b times). How does this help us define the problem recursively?

15 Solution Product.scala

16 Recursion - Exercise 2 Given the following iterative version of sum- of-digits calculation Write the recursive definition

17 Solution SumDigits.scala

18 Today Home work review Guest lecture by Prof. Benny Chor Recursive vs. Iterative Arrays Sorting, searching and time-complexity analysis Home work

19 Compute a b Iteratively Operationally: Halting condition: product  product * a counter  counter - 1 counter = 0 a b = a 2 *a*…*a = a 3 *…*a Which is: a b = a * a * a*…*a b

20 Compute a b Iteratively

21 Compute a b (Recursive Approach) Recursive call: a b = a * a (b-1) Base case: a 0 = 1

22 Compute a b (Iterative Approach) How then, do the two procedures differ?

23 Recursive Process powRec(3,4) 3 * powRec(3,3) 3 * (3 * powRec(3,2)) 3 * (3 * (3 * powRec(3,1))) 3 * (3 * (3 * (3 * powRec(3,0)))) 3 * (3 * (3 * (3 * 1))) 3 * (3 * (3 * 3)) 3 * (3 * 9) a * 27 81

24 Iterative Process powTailRec(3,4) pow1(3,4,1) pow1(3,3,3) pow1(3,2,9) pow1(3,1,27) pow1(3,0,81) 81

25 powRec(3,4) 3 * powRec(3,3) 3 * (3 * powRec(3,2)) 3 * (3 * (3 * powRec(3,1))) 3 * (3 * (3 * (3 * powRec(3,0)))) 3 * (3 * (3 * (3 * 1))) 3 * (3 * (3 * 3)) 3 * (3 * 9) a * The Difference Growing amount of space Constant amount of space powTailRec(3,4) pow1(3,4,1) pow1(3,3,3) pow1(3,2,9) pow1(3,1,27) pow1(3,0,81) 81

26 Why More Space? Operation pending No pending operations

27 Summary Recursive process num of deferred operations “grows proportional to b” Iterative process num of deferred operations stays “constant” (actually it’s zero) Can we better quantify these observations?

28 Order of Growth: Recursive Process powRec(3,5) 3 * powRec(3,4) 3 * (3 * powRec(3,3)) 3 * (3 * (3 * powRec(3,2))) 3 * (3 * (3 * (3 * powRec(3,1)))) 3 * (3 * (3 * (3 * (3 * powRec(3,0))))) 3 * (3 * (3 * (3 * (3 * 1)))) 3 * (3 * (3 * (3 * 3))) 3 * (3 * (3 * 9)) 3 * (3 * 27) a * powRec(3,4) 3 * powRec(3,3) 3 * (3 * powRec(3,2)) 3 * (3 * (3 * powRec(3,1))) 3 * (3 * (3 * (3 * powRec(3,0)))) 3 * (3 * (3 * (3 * 1))) 3 * (3 * (3 * 3)) 3 * (3 * 9) a * Dependent on b

29 Order of Growth: Iterative Process powTailRec(3,5) pow1(3,5,1) pow1(3,4,3) pow1(3,3,9) pow1(3,2,27) pow1(3,1,81) pow1(3,0,243) 243 powTailRec(3,4) pow1(3,4,1) pow1(3,3,3) pow1(3,2,9) pow1(3,1,27) pow1(3,0,81) 81 Same constant, independent of b

30 “Tail” Recursion in Scala Scala compiler translate tail-recursion to iterative execution Thus, the functions-stack is not growing

31 Today Home work review Guest lecture by Prof. Benny Chor Recursive vs. Iterative Arrays Sorting, searching and time-complexity analysis Home work

32 Arrays Array: sequential block of memory that holds variables of the same type Array can be declared for any type Example: new Array[Int](3) Examples: list of students’ marks series of numbers entered by user vectors matrices

33 Arrays in Memory Sequence of variables of specified type The array variable itself holds the address in memory of beginning of sequence Example: val s = new Array[Double](10) The k-th element of array A is specified by A[k-1] (0 based) s ……

34 Example - Initialization

35 Arrays in Memory Access array’s content Change array’s content

36 Example Array.scala

37 foreach, filter Iterates over arrays (and other containers) foreach – for each element apply a given function filter – create a new container containing only elements that pass the given Boolean-function

38 Example – Print Arrays PrintArray.scala

39 Example – filter

40 Example – Find Minimum FindMin.scala

41 Arrays as Function Arguments Functions can accept arrays as arguments Example: Within the function, arr is accessed in the usual way Changes to the array in the function change the original array! (why?)

42 Example ArraySum.scala

43 Example MultAll.scala

44 Efficient Factorial Write a program that repeatedly receives a natural number as its input and returns its factorial The maximal number that will be given is known to be 1000 The program should be efficient: Do not calculate 1*2*…*n for every n from the beginning on every input Do not calculate values that were not requested

45 Solution: Main Idea We can keep in an array the results When given a new n If calculated before – return it Otherwise, get a better start

46 Solution EfficientFact.scala

47 Solution (main) EfficientFact.scala

48 Multi-Dimensional Arrays Array of arrays: val arr = Array[Array[Int]](3,2) Means an array of 3 integer arrays, each of length 2 Access: j th element of the i th array is a[i][j]

49 References to Arrays What is going on here?

50 In Memory 321 x1 x2 100

51 Today Home work review Guest lecture by Prof. Benny Chor Recursive vs. Iterative Arrays Sorting, searching and time-complexity analysis Home work

52 Sort We would like to sort the elements in an array in an ascending order sort

53 What is Sorting Good For? Finding a number in an array Consider a large array (of length n) and multiple queries on whether a given number exists in the array (and what is its position in it) Naive solution: given a number, traverse the array and search for it Not efficient ~ n/2 steps for each search operation Can we do better? Sort the array as a preliminary step. Now search can be performed much faster!

54 Binary Search Input: A sorted array of integers A An integer query q Output: -1 if q is not a member of A The index of q in A otherwise Algorithm: Check the middle element of A If it is equal to q, return its index If it is >= q, search for q in A[0,…,middle-1] If it is < q, search for q in A[middle+1,...,end]

55 Example index value

56 Today Home work review Guest lecture by Prof. Benny Chor Recursive vs. Iterative Arrays Sorting, searching and time-complexity analysis Home work

57 Exercise 1 Write a program that gets 10 numbers from the user. It then accepts another number and checks to see if that number was one of the previous ones. Example 1: Please enter 10 numbers: Please enter a number to search for: 8 Found it! Example 2: Please enter 10 numbers: Please enter a number to search for: 30 Sorry, it’s not there

58 Exercise 2 Implement a function that accepts two integer arrays and returns true if they are equal, false otherwise. The arrays are of the same size Write a program that accepts two arrays of integers from the user and checks for equality