UNIT 5B Binary Search

Size: px
Start display at page:

Download "UNIT 5B Binary Search"

Transcription

1 205/09/30 UNIT 5B Binary Search Course Announcements Written exam next week (Wed. Oct 7 ) Practice exam available on the Resources page Exam reviews: Sunday afternoon; watch Piazza for times and places Problem Set 5 will be due as usual on the Friday after the exam. Programming Assignment 5 will be due Monday after exam. 2

2 This Lecture A new search technique for lists called binary search Application of recursion to binary search Logarithmic worst-case complexity 3 but first, return to Monday s slides on FIBONACCI NUMBERS 4 2

3 Fibonacci Numbers A sequence of numbers: Fibonacci Numbers in Nature 0,,, 2, 3, 5, 8, 3, 2, 34, 55, 89, 44, 233, etc. Number of branches on a tree, petals on a flower, spirals on a pineapple. Vi Hart's video on Fibonacci numbers (

4 Recursive Definition Let fib(n) = the nth Fibonacci number, n 0 fib(0) = 0 (base case) fib() = (base case) fib(n) = fib(n-) + fib(n-2), n > 0,,, 2, 3, 5, 8, 3, 2, 34, 55, 89, 44, 233, etc def fib(n): if n == 0 or n == : return n" Two recursive calls! " else: " " return fib(n-) + fib(n-2)" 20 Recursive Call Tree fib(5) fib(4) fib(3) fib(3) fib(2) fib(2) fib() fib(2) fib() fib() fib(0) fib() fib(0) fib() fib(0) fib(0) = 0 fib() = fib(n) = fib(n-) + fib(n-2), n > 22 4

5 Recursive Call Tree 4 fib(5) 3 fib(4) 2 fib(3) 2 fib(3) fib(2) fib(2) fib() fib(2) fib() 0 fib() fib(0) fib() 0 fib(0) 0 fib() fib(0) fib(0) = 0 fib() = fib(n) = fib(n-) + fib(n-2), n > 22 the idea BINARY SEARCH 0 5

6 Number guessing I'm thinking of a number between and 6 You get to ask me, yes or no, is it greater than some number you choose Which questions will you ask to get the answer quickest? How many questions do you need to ask? Binary Search in an Ordered List? 2 6

7 Binary Search in an Ordered List 00 pixels 87 pixels? 3 Binary Search in an Ordered List 9 pixels 87 pixels? 4 7

8 Binary Search in an Ordered List 83 pixels? 87 pixels 5 Binary Search in an Ordered List 87 pixels 87 pixels! 6 8

9 from idea to ALGORITHM 7 Specification: the Search Problem Input: A list of n unique elements and a key to search for The elements are sorted in increasing order. Result: The index of an element matching the key, or None if the key is not found. 4 9

10 Recursive Algorithm BinarySearch(list, key):. If the list is empty, return None. 2. Compare the key to the middle element of the list. 3. Return the index of the middle element if they match. 4. If the key is less than the middle element then return BinarySearch(first half of list, key) Otherwise, return BinarySearch(second half of list, key). 8 Example : Search for Found: return 9 0

11 Example 2: Search for Not found: return None Controlling the range of the search Maintain three numbers: lower, upper, mid Initially lower is -, upper is length of the list lower = - upper = 2 0

12 Controlling the range of the search mid is the midpoint of the range: mid = (lower + upper) // 2 (integer division) Example: lower = -, upper = 9 (range has 9 elements) mid = 4 What happens if the range has an even number of elements? Example: lower = -, upper = 8 mid = 3 Example D? A B C D E F G H I lower = - upper = 9 mid = 4 List sorted in ascending order. Suppose we are searching for D. 5 2

13 D? Example A B C D E F G H I lower = - upper = 4 mid = we look at a smaller por@on of the list within the window and ignore all the elements outside of the window 6 D? Example A B C D E F G H I lower = upper = 4 mid = 2 we look at a smaller por@on of the array within the window and ignore all the elements outside of the window 7 3

14 Example D! A B C D E F G H I lower = 2 upper = 4 mid = 3 we look at a smaller por@on of the array within the window and ignore all the elements outside of the window 7 towards a Python program: DESIGNING THE RECURSION 28 4

15 Base case: range empty How do we determine if the range is empty? lower + == upper What should we return then? None 2 Base case: key found The key is compared to the element at mid: list[mid] == key What should we return then? mid 2 5

16 Recursive Case Non-empty range: what subproblem(s) should we solve? search left half or search right half What should we return then? result of searching left or right half New value for lower? value for upper? left half: lower, mid right half: mid, upper 2 Parameters for recursion Inputs: key and list of items But we also need lower and upper bounds since they change throughout the search, they have to be parameters of the search function Design: main function and recursive helper function 32 6

17 Recursive Binary Search in Python first value for upper " first value for lower # main function" def bsearch(items, key):" return bs_helper(items, key, -, len(items))" " # recursive helper function" def bs_helper(items, key, lower, upper):" if lower + == upper: # Base case: empty" return None" mid = (lower + upper) // 2" if key == items[mid]: # Base case: found " return mid" new value for upper # Recursive cases " same value for lower if key < items[mid]: # Go left" return bs_helper(items, key, lower, mid)" else: # Go right" return bs_helper(items, key, mid, upper)" new value for lower same value for upper 3 Caveat: specification The algorithm and the code was developed on the assumption that the input list is sorted. If the function is called with an unsorted list it has no obligation to behave correctly. 5 7

18 reflections MEASUREMENT AND ANALYSIS 35 Trace: Search for key lower upper bs_helper(items, 73, -, 5)" " " " " " mid = 7 and 73 > items[7]" bs_helper(items, 73, 7, 5)" " " " " " mid = and 73 < items[]" bs_helper(items, 73, 7, )" " " " " " mid = 9 and 73 == items[9]" " " " " " --->"return 9" 8

19 Trace: Search for key lower upper bs_helper(items, 42, -, 5)" " " " " " mid = 7 and 42 < items[7]" bs_helper(items, 42, -, 7)" " " " " " mid = 3 and 42 > items[3]" bs_helper(items, 42, 3, 7)" " " " " " mid = 5 and 42 < items[5]" bs_helper(items, 42, 3, 5)" " " " " " mid = 4 and 42 > items[4]" bs_helper(items, 73, 4, 5)" " " " " " lower + == upper " " " " " " ---> Return None" Instrumenting Binary Search Code count = 0 # count of comparisons" " def bsearch(list, key):" global count" count = 0" print("searching list of length ", len(list))" result = bs_helper(list, key, -, len(list))" print("number of comparisons:", count)" return result" " def bs_helper(list, key, lower, upper):" global count" if lower + == upper:" print("not found")" return None" mid = (lower + upper) // 2" print("mid:", mid, "lower:", lower, "upper", upper)" count = count + " if key == list[mid]: " return mid" if key < list[mid]:" return bs_helper(list, key, lower, mid)" else:" return bs_helper(list, key, mid, upper)" 8 9

20 Instrumented Output >>> bsearch(list(range(,500,2)), 2) Searching list of length 250 mid: 24 lower: - upper 250 mid: 6 lower: - upper 24 mid: 30 lower: - upper 6 mid: 4 lower: - upper 30 mid: 6 lower: - upper 4 mid: 0 lower: 6 upper 4 Number of comparisons: 6 0 >>> bsearch(list(range(,500,2)), 256) Searching list of length 250 mid: 24 lower: - upper 250 mid: 87 lower: 24 upper 250 mid: 55 lower: 24 upper 87 mid: 39 lower: 24 upper 55 mid: 3 lower: 24 upper 39 mid: 27 lower: 24 upper 3 mid: 29 lower: 27 upper 3 mid: 28 lower: 27 upper 29 Not found Number of comparisons: 8 >>> bsearch(list(range(,500000,2)), 256) Searching list of length mid: lower: - upper mid: 27 lower: 26 upper 28 Not found Number of comparisons: 8 >>> bsearch(list(range(, ,2)), 256) Searching list of length mid: lower: - upper mid: 28 lower: 27 upper 29 Not found Number of comparisons: 2 When is the worst case? 39 Analyzing Binary Search Suppose we search for a key larger than anything in the list. Example sequences of range sizes: 8, 4, 2, (4 key comparisons) 6, 8, 4, 2, (5 key comparisons) 7, 8, 4, 2, (5 key comparisons) 8, 9, 4, 2, (5 key comparisons)... 3, 5, 7, 3, (still 5 key comparisons) 32, 6, 8, 4, 2, (at last, 6 key comparisons) Notice: 8 = 2 3, 6 = 2 4, 32 = 2 5, Therefore: log 2 8 = 3, log 2 6 = 4, log 2 32 =

21 Generalizing the Analysis floor Some notation: x means round x down, so 2.5 =2 Binary search of n elements will do at most + log 2 n comparisons + log 2 8 = + log 2 9 =... + log 2 5 = 4 + log 2 6 = + log 2 7 =... + log 2 3 = 5 Why? We can split search region in half + log 2 n times before it becomes empty. "Big O" notation: we ignore the + and the floor function. We say Binary Search has complexity O(log n). 22 O(log n) ( logarithmic time ) 2(log 2 n) + 5 Number of Operations log 2 n log 0 n log a (x) = log a (b) log b (x) constant n (amount of data) 24 2

22 Number of Operations O(log n) For a log 2 n algorithm, If you double the number of data elements the amount of work you do increases by just one unit Add one log 2 n Double n (amount of data) 25 Binary Search (Worst Case) Number of elements Number of Comparisons million 20 billion

23 Binary Search Pays Off Finding an element in an list with a million elements requires only 20 comparisons! BUT... The list must be sorted. What if we sort the list first using insertion sort? Insertion sort O(n 2 ) (worst case) Binary search O(log n) (worst case) Total time: O(n 2 ) + O(log n) = O(n 2 ) Luckily there are faster ways to sort in the worst case Next Time Merge Sort: a faster sorting algorithm image:

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements.

15110 Principles of Computing, Carnegie Mellon University - CORTINA. Binary Search. Required: List L of n unique elements. UNIT 5B Binary Search 1 Binary Search Required: List L of n unique elements. The elements must be sorted in increasing order. Result: The index of a specific element (called the key) or None if the key

More information

UNIT 5C Merge Sort. Course Announcements

UNIT 5C Merge Sort. Course Announcements UNIT 5C Merge Sort 15110 Principles of Computing, Carnegie Mellon University 1 Course Announcements Exam information 2:30 Lecture: Sections F, G, H will go to HH B131. 3:30 Lecture: Section O will go to

More information

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return Recursion CS 1 Admin How's the project coming? After these slides, read chapter 13 in your book Yes that is out of order, but we can read it stand alone Quizzes will return Tuesday Nov 29 th see calendar

More information

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY Computer Science Foundation Exam Dec. 19, 2003 COMPUTER SCIENCE I Section I A No Calculators! Name: KEY SSN: Score: 50 In this section of the exam, there are Three (3) problems You must do all of them.

More information

Recall from Last Time: Big-Oh Notation

Recall from Last Time: Big-Oh Notation CSE 326 Lecture 3: Analysis of Algorithms Today, we will review: Big-Oh, Little-Oh, Omega (Ω), and Theta (Θ): (Fraternities of functions ) Examples of time and space efficiency analysis Covered in Chapter

More information

CSCI 121: Recursive Functions & Procedures

CSCI 121: Recursive Functions & Procedures CSCI 121: Recursive Functions & Procedures Sorting quizzes Every time I give a quiz, I need to enter grades into my gradebook. My grading sheet is organized alphabetically. So I sort the papers alphabetically,

More information

CSc 110, Spring 2017 Lecture 39: searching

CSc 110, Spring 2017 Lecture 39: searching CSc 110, Spring 2017 Lecture 39: searching 1 Sequential search sequential search: Locates a target value in a list (may not be sorted) by examining each element from start to finish. Also known as linear

More information

CSC236 Week 5. Larry Zhang

CSC236 Week 5. Larry Zhang CSC236 Week 5 Larry Zhang 1 Logistics Test 1 after lecture Location : IB110 (Last names A-S), IB 150 (Last names T-Z) Length of test: 50 minutes If you do really well... 2 Recap We learned two types of

More information

Algorithm Design and Recursion. Search and Sort Algorithms

Algorithm Design and Recursion. Search and Sort Algorithms Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms

More information

Computer Algorithms. Introduction to Algorithm

Computer Algorithms. Introduction to Algorithm Computer Algorithms Introduction to Algorithm CISC 4080 Yanjun Li 1 What is Algorithm? An Algorithm is a sequence of well-defined computational steps that transform the input into the output. These steps

More information

Binary Search APRIL 25 TH, 2014

Binary Search APRIL 25 TH, 2014 Binary Search APRIL 25 TH, 2014 The Search Problem One of the most common computational problems (along with sorting) is searching. In its simplest form, the input to the search problem is a list L and

More information

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place? Sorting Binary search works great, but how do we create a sorted array in the first place? Sorting in Arrays Sorting algorithms: Selection sort: O(n 2 ) time Merge sort: O(nlog 2 (n)) time Quicksort: O(n

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Searching data involves determining whether a value (referred to as the search key) is present in the data

More information

Algorithmics. Some information. Programming details: Ruby desuka?

Algorithmics. Some information. Programming details: Ruby desuka? Algorithmics Bruno MARTIN, University of Nice - Sophia Antipolis mailto:bruno.martin@unice.fr http://deptinfo.unice.fr/~bmartin/mathmods.html Analysis of algorithms Some classical data structures Sorting

More information

Searching Algorithms/Time Analysis

Searching Algorithms/Time Analysis Searching Algorithms/Time Analysis CSE21 Fall 2017, Day 8 Oct 16, 2017 https://sites.google.com/a/eng.ucsd.edu/cse21-fall-2017-miles-jones/ (MinSort) loop invariant induction Loop invariant: After the

More information

Recursion continued. Programming using server Covers material done in Recitation. Part 2 Friday 8am to 4pm in CS110 lab

Recursion continued. Programming using server Covers material done in Recitation. Part 2 Friday 8am to 4pm in CS110 lab Recursion continued Midterm Exam 2 parts Part 1 done in recitation Programming using server Covers material done in Recitation Part 2 Friday 8am to 4pm in CS110 lab Question/Answer Similar format to Inheritance

More information

UNIT 5A Recursion: Basics. Recursion

UNIT 5A Recursion: Basics. Recursion UNIT 5A Recursion: Basics 1 Recursion A recursive function is one that calls itself. Infinite loop? Not necessarily. 2 1 Recursive Definitions Every recursive definition includes two parts: Base case (non

More information

ECE 122. Engineering Problem Solving Using Java

ECE 122. Engineering Problem Solving Using Java ECE 122 Engineering Problem Solving Using Java Lecture 27 Linear and Binary Search Overview Problem: How can I efficiently locate data within a data structure Searching for data is a fundamental function

More information

(Refer Slide Time: 01.26)

(Refer Slide Time: 01.26) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture # 22 Why Sorting? Today we are going to be looking at sorting.

More information

https://cs.uiowa.edu/resources/events Searching an array Let R(N) be the running time to search for an integer in an unsorted array. Can we find an f(n) such that R N O(f N )? Searching an array Let R(N)

More information

QB LECTURE #1: Algorithms and Dynamic Programming

QB LECTURE #1: Algorithms and Dynamic Programming QB LECTURE #1: Algorithms and Dynamic Programming Adam Siepel Nov. 16, 2015 2 Plan for Today Introduction to algorithms Simple algorithms and running time Dynamic programming Soon: sequence alignment 3

More information

CS 4800: Algorithms & Data. Lecture 1 January 10, 2017

CS 4800: Algorithms & Data. Lecture 1 January 10, 2017 CS 4800: Algorithms & Data Lecture 1 January 10, 2017 Huy L. Nguyen Email: hu.nguyen@northeastern.edu Office hours: Tuesday 1:20 3:20, WVH 358 Research: Algorithms for massive data sets ( big data ) Theoretical

More information

Outline: Search and Recursion (Ch13)

Outline: Search and Recursion (Ch13) Search and Recursion Michael Mandel Lecture 12 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture12final.ipynb

More information

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique.

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique. Recursion 1 What is Recursion? Solution given in terms of problem. Huh? Each problem is a smaller instance of itself. Implemented via functions. Very powerful solving technique. Base Case and Recursive

More information

For searching and sorting algorithms, this is particularly dependent on the number of data elements.

For searching and sorting algorithms, this is particularly dependent on the number of data elements. Looking up a phone number, accessing a website and checking the definition of a word in a dictionary all involve searching large amounts of data. Searching algorithms all accomplish the same goal finding

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 11, 2017 Outline Outline 1 Chapter 6: Recursion Outline Chapter 6: Recursion 1 Chapter 6: Recursion Measuring Complexity

More information

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3... Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial

More information

Module 08: Searching and Sorting Algorithms

Module 08: Searching and Sorting Algorithms Module 08: Searching and Sorting Algorithms Topics: Searching algorithms Sorting algorithms 1 Application: Searching a list Suppose you have a list L. How could you determine if a particular value is in

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College August 31, 2015 Outline Outline 1 Chapter 1 Outline Textbook Data Structures and Algorithms Using Python and C++ David M.

More information

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson Component 02 Algorithms and programming Sorting Algorithms and Searching Algorithms 1 BUBBLE SORT Bubble sort is a brute force and iterative sorting algorithm where each adjacent item in the array is compared.

More information

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion Outline 1 A Function Can Call Itself A recursive definition of a function is one which makes a function call to the function being defined. The function call is then a recursive function call. A definition

More information

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion 2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits

More information

COMP 250 Fall recurrences 2 Oct. 13, 2017

COMP 250 Fall recurrences 2 Oct. 13, 2017 COMP 250 Fall 2017 15 - recurrences 2 Oct. 13, 2017 Here we examine the recurrences for mergesort and quicksort. Mergesort Recall the mergesort algorithm: we divide the list of things to be sorted into

More information

Binary Search and Worst-Case Analysis

Binary Search and Worst-Case Analysis Department of Computer Science and Engineering Chinese University of Hong Kong A significant part of computer science is devoted to understanding the power of the RAM model in solving specific problems.

More information

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims Lecture 10: Asymptotic Complexity and What Makes a Good Algorithm? Suppose you have two possible algorithms or

More information

Recursion: The Beginning

Recursion: The Beginning Department of Computer Science and Engineering Chinese University of Hong Kong This lecture will introduce a useful technique called recursion. If used judiciously, this technique often leads to elegant

More information

15-110: Principles of Computing, Spring 2018

15-110: Principles of Computing, Spring 2018 15-110: Principles of Computing, Spring 2018 Problem Set 5 (PS5) Due: Friday, February 23 by 2:30PM via Gradescope Hand-in HANDIN INSTRUCTIONS Download a copy of this PDF file. You have two ways to fill

More information

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling Recursion Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling With reference to the call stack Compute the result of simple recursive algorithms Understand

More information

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

9/10/12. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3) Outline Part 5. Computational Complexity (2) Complexity of Algorithms Efficiency of Searching Algorithms Sorting Algorithms and Their Efficiencies CS 200 Algorithms and Data Structures 1 2 (revisit) Properties

More information

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19 Data Structures Alice E. Fischer Lecture 4, Fall 2018 Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall 2018 1 / 19 Outline 1 Ordered Lists 2 Sorted Lists Tail Pointers 3 Doubly Linked Lists

More information

CSC236H Lecture 5. October 17, 2018

CSC236H Lecture 5. October 17, 2018 CSC236H Lecture 5 October 17, 2018 Runtime of recursive programs def fact1(n): if n == 1: return 1 else: return n * fact1(n-1) (a) Base case: T (1) = c (constant amount of work) (b) Recursive call: T

More information

Sum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient?

Sum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient? Sum this up for me Let s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i

More information

CS171 Midterm Exam. October 29, Name:

CS171 Midterm Exam. October 29, Name: CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and

More information

2/14/13. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3)

2/14/13. Outline. Part 5. Computational Complexity (2) Examples. (revisit) Properties of Growth-rate functions(1/3) Outline Part 5. Computational Complexity (2) Complexity of Algorithms Efficiency of Searching Algorithms Sorting Algorithms and Their Efficiencies CS 200 Algorithms and Data Structures 1 2 (revisit) Properties

More information

Introduction to Programming I

Introduction to Programming I Still image from YouTube video P vs. NP and the Computational Complexity Zoo BBM 101 Introduction to Programming I Lecture #09 Development Strategies, Algorithmic Speed Erkut Erdem, Aykut Erdem & Aydın

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 0-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time CISC101 Reminders & Notes Test 3 this week in tutorial USATs at the beginning of next lecture Please attend and fill out an evaluation School of Computing First Year Information Session Thursday, March

More information

Complexity of Algorithms

Complexity of Algorithms Complexity of Algorithms Time complexity is abstracted to the number of steps or basic operations performed in the worst case during a computation. Now consider the following: 1. How much time does it

More information

The Limits of Sorting Divide-and-Conquer Comparison Sorts II

The Limits of Sorting Divide-and-Conquer Comparison Sorts II The Limits of Sorting Divide-and-Conquer Comparison Sorts II CS 311 Data Structures and Algorithms Lecture Slides Monday, October 12, 2009 Glenn G. Chappell Department of Computer Science University of

More information

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming

More information

Sorting and Selection

Sorting and Selection Sorting and Selection Introduction Divide and Conquer Merge-Sort Quick-Sort Radix-Sort Bucket-Sort 10-1 Introduction Assuming we have a sequence S storing a list of keyelement entries. The key of the element

More information

COMP 364: Computer Tools for Life Sciences

COMP 364: Computer Tools for Life Sciences COMP 364: Computer Tools for Life Sciences Algorithm design: Linear and Binary Search Mathieu Blanchette, based on material from Christopher J.F. Cameron and Carlos G. Oliver 1 / 24 Algorithms An algorithm

More information

Recursion. Fundamentals of Computer Science

Recursion. Fundamentals of Computer Science Recursion Fundamentals of Computer Science Outline Recursion A method calling itself All good recursion must come to an end A powerful tool in computer science Allows writing elegant and easy to understand

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Administrivia and Motivation Administrative Matters: Review of course design and course policies Motivation: Two Algorithms

More information

CSE 373 APRIL 3 RD ALGORITHM ANALYSIS

CSE 373 APRIL 3 RD ALGORITHM ANALYSIS CSE 373 APRIL 3 RD ALGORITHM ANALYSIS ASSORTED MINUTIAE HW1P1 due tonight at midnight HW1P2 due Friday at midnight HW2 out tonight Second Java review session: Friday 10:30 ARC 147 TODAY S SCHEDULE Algorithm

More information

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June

More information

Sorting Pearson Education, Inc. All rights reserved.

Sorting Pearson Education, Inc. All rights reserved. 1 19 Sorting 2 19.1 Introduction (Cont.) Sorting data Place data in order Typically ascending or descending Based on one or more sort keys Algorithms Insertion sort Selection sort Merge sort More efficient,

More information

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012 RECURSION 7 COMPUTER SCIENCE 61A October 15, 2012 1 Recursion We say a procedure is recursive if it calls itself in its body. Below is an example of a recursive procedure to find the factorial of a positive

More information

SORTING AND SEARCHING

SORTING AND SEARCHING SORTING AND SEARCHING Today Last time we considered a simple approach to sorting a list of objects. This lecture will look at another approach to sorting. We will also consider how one searches through

More information

UNIT 5C Merge Sort Principles of Computing, Carnegie Mellon University

UNIT 5C Merge Sort Principles of Computing, Carnegie Mellon University UNIT 5C Merge Sort 15110 Principles of Computing, Carnegie Mellon University 1 Divide and Conquer In computation: Divide the problem into simpler versions of itself. Conquer each problem using the same

More information

6.00 Notes On Big-O Notation

6.00 Notes On Big-O Notation 6.00 Notes On Big-O Notation April 13, 2011 Sarina Canelake See also http://en.wikipedia.org/wiki/big O notation We use big-o notation in the analysis of algorithms to describe an algorithm s usage of

More information

15-110: Principles of Computing Sample Exam #1

15-110: Principles of Computing Sample Exam #1 15-110: Principles of Computing Sample Exam #1 The following is a "sample exam" that you can use to practice after you have studied for the exam. Keep in mind that the actual exam will have its own questions,

More information

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications?

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications? Calculate x y The power of logarithmic computations // Pre: x 0, y 0 // Returns x y int power(int x, int y) { int p = 1; for (int i = 0; i < y; ++i) p = p x; return p; Jordi Cortadella Department of Computer

More information

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018 CSCI Data Structures 1 Analysis of Recursive Algorithms, Binary Search, Analysis of RECURSIVE ALGORITHMS Recursive Function Analysis Here s a simple recursive function which raises one number to a (non-negative)

More information

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1 Math 4242 Fibonacci, Memoization lecture 13 Today we talk about a problem that sometimes occurs when using recursion, and a common way to fix it. Recall the Fibonacci sequence (F 0, F 1, F 2,...) that

More information

Binary Search to find item in sorted array

Binary Search to find item in sorted array Binary Search to find item in sorted array January 15, 2008 QUESTION: Suppose we are given a sorted list A[1..n] (as an array), of n real numbers: A[1] A[2] A[n]. Given a real number x, decide whether

More information

CS 151. Recursion (Review!) Wednesday, September 19, 12

CS 151. Recursion (Review!) Wednesday, September 19, 12 CS 151 Recursion (Review!) 1 Announcements no class on Friday, and no office hours either (Alexa out of town) unfortunately, Alexa will also just be incommunicado, even via email, from Wednesday night

More information

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution Agenda The worst algorithm in the history of humanity 1 Asymptotic notations: Big-O, Big-Omega, Theta An iterative solution A better iterative solution The repeated squaring trick Fibonacci sequence 2

More information

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 7 Quicksort 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In this lecture we consider two related algorithms for sorting that achieve a much better running time than

More information

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I

Searching for Information. A Simple Method for Searching. Simple Searching. Class #21: Searching/Sorting I Class #21: Searching/Sorting I Software Design II (CS 220): M. Allen, 26 Feb. 18 Searching for Information Many applications involve finding pieces of information Finding a book in a library or store catalogue

More information

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return 0. How would we write the BinaryHeap siftdown function recursively? [0] 6 [1] [] 15 10 Name: template class BinaryHeap { private: int maxsize; int numitems; T * heap;... [3] [4] [5] [6] 114 0

More information

For 100% Result Oriented IGNOU Coaching and Project Training Call CPD: ,

For 100% Result Oriented IGNOU Coaching and Project Training Call CPD: , ASSIGNMENT OF MCS-031(ADA) Question 1: (a) Show, through appropriate examples or otherwise, that the following three characteristics of an algorithm are independent (i) finiteness An algorithm must terminate

More information

Recursion: The Beginning

Recursion: The Beginning Yufei Tao ITEE University of Queensland This lecture is the inception of a powerful technique called recursion. If used judiciously, this technique can simplify the design of an algorithm significantly,

More information

Binary Search and Worst-Case Analysis

Binary Search and Worst-Case Analysis Yufei Tao ITEE University of Queensland A significant part of computer science is devoted to understanding the power of the RAM model in solving specific problems. Every time we discuss a problem in this

More information

[ 11.2, 11.3, 11.4] Analysis of Algorithms. Complexity of Algorithms. 400 lecture note # Overview

[ 11.2, 11.3, 11.4] Analysis of Algorithms. Complexity of Algorithms. 400 lecture note # Overview 400 lecture note #0 [.2,.3,.4] Analysis of Algorithms Complexity of Algorithms 0. Overview The complexity of an algorithm refers to the amount of time and/or space it requires to execute. The analysis

More information

Recursion: The Mirrors. (Walls & Mirrors - Chapter 2)

Recursion: The Mirrors. (Walls & Mirrors - Chapter 2) Recursion: The Mirrors (Walls & Mirrors - Chapter 2) 1 To iterate is human, to recurse, divine. - L. Peter Deutsch It seems very pretty but it s rather hard to understand! - Lewis Carroll 2 A recursive

More information

Recursion. Recursion [Bono] 1

Recursion. Recursion [Bono] 1 Recursion Idea A few examples wishful thinking method Recursion in classes Ex: palindromes Helper functions Computational complexity of recursive functions Recursive functions with multiple calls Recursion

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02) Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 04 Lecture - 01 Merge Sort (Refer

More information

Sorting: Overview/Questions

Sorting: Overview/Questions CS121: Sorting and Searching Algorithms John Magee 24 April 2012 1 Sorting: Overview/Questions What is sorting? Why does sorting matter? How is sorting accomplished? Why are there different sorting algorithms?

More information

Measuring Efficiency

Measuring Efficiency Growth Announcements Measuring Efficiency Recursive Computation of the Fibonacci Sequence Our first example of tree recursion: fib(3) fib(5) fib(4) def fib(n): if n == 0: return 0 elif n == 1: return 1

More information

algorithm evaluation Performance

algorithm evaluation Performance algorithm evaluation sorting, Big 0 1 Performance formal experimental Correctness / understandability qualitative software metrics Big O, for initial design considerations "big" high level analysis, "O"

More information

Theory and Frontiers of Computer Science. Fall 2013 Carola Wenk

Theory and Frontiers of Computer Science. Fall 2013 Carola Wenk Theory and Frontiers of Computer Science Fall 2013 Carola Wenk We have seen so far Computer Architecture and Digital Logic (Von Neumann Architecture, binary numbers, circuits) Introduction to Python (if,

More information

Recursion. John Ross Wallrabenstein

Recursion. John Ross Wallrabenstein Recursion John Ross Wallrabenstein Recursion: The Black Magic of Programming Learning the Dark Art Theory Definition Constructing a Recursive Function Definition Practice Implementation and Data Structures

More information

CS/CE 2336 Computer Science II

CS/CE 2336 Computer Science II S/E 2336 omputer Science II UT D Session 10 Recursion dapted from D Liang s Introduction to Java Programming, 8 th Ed 2 factorial(0) = 1; omputing Factorial factorial(n) = n*factorial(n-1); n! = n * (n-1)!

More information

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ). Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There

More information

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ). /2/8 Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem?

More information

LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS

LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS Department of Computer Science University of Babylon LECTURE NOTES OF ALGORITHMS: DESIGN TECHNIQUES AND ANALYSIS By Faculty of Science for Women( SCIW), University of Babylon, Iraq Samaher@uobabylon.edu.iq

More information

CSCI-1200 Data Structures Fall 2017 Lecture 7 Order Notation & Basic Recursion

CSCI-1200 Data Structures Fall 2017 Lecture 7 Order Notation & Basic Recursion CSCI-1200 Data Structures Fall 2017 Lecture 7 Order Notation & Basic Recursion Announcements: Test 1 Information Test 1 will be held Monday, Sept 25th, 2017 from 6-7:50pm Students will be randomly assigned

More information

Divide and Conquer Algorithms: Advanced Sorting

Divide and Conquer Algorithms: Advanced Sorting Divide and Conquer Algorithms: Advanced Sorting (revisit) Properties of Growth-rate functions(1/3) 1. You can ignore low-order terms in an algorithm's growth-rate function. O(n 3 +4n 2 +3n) it is also

More information

Search and Sorting Algorithms

Search and Sorting Algorithms Fundamentals of Programming (Python) Search and Sorting Algorithms Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Introduction. two of the most fundamental concepts in computer science are, given an array of values:

Introduction. two of the most fundamental concepts in computer science are, given an array of values: Searching Class 28 Introduction two of the most fundamental concepts in computer science are, given an array of values: search through the values to see if a specific value is present and, if so, where

More information

Divide and Conquer. playing divide and conquer. searching in a sorted list membership in a sorted list

Divide and Conquer. playing divide and conquer. searching in a sorted list membership in a sorted list Divide and Conquer 1 Guessing a Secret playing divide and conquer 2 Binary Search searching in a sorted list membership in a sorted list 3 Bisection Search inverting a sampled function bisection search

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Week 02 Module 06 Lecture - 14 Merge Sort: Analysis So, we have seen how to use a divide and conquer strategy, we

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 6 - Faster Sorting Methods Merge Sort Divides an array into halves Sorts the two halves, Then merges them into one sorted array. The algorithm for merge sort is usually

More information

COE428 Lecture Notes Week 1 (Week of January 9, 2017)

COE428 Lecture Notes Week 1 (Week of January 9, 2017) COE428 Lecture Notes: Week 1 1 of 10 COE428 Lecture Notes Week 1 (Week of January 9, 2017) Table of Contents COE428 Lecture Notes Week 1 (Week of January 9, 2017)...1 Announcements...1 Topics...1 Informal

More information

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4) Orders of Growth of Processes Today s topics Resources used by a program to solve a problem of size n Time Space Define order of growth Visualizing resources utilization using our model of evaluation Relating

More information

CS1 Lecture 15 Feb. 19, 2018

CS1 Lecture 15 Feb. 19, 2018 CS1 Lecture 15 Feb. 19, 2018 HW4 due Wed. 2/21, 5pm (changed from original 9am so people in Wed. disc. sections can get help) Q2: find *any* solution. Don t try to find the best/optimal solution or all

More information

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,

More information

Wednesday January 31, 2:30-4pm ENGMC 103

Wednesday January 31, 2:30-4pm ENGMC 103 Academic Forum Wednesday January 31, 2:30-4pm ENGMC 103 The academic forum is an opportunity for students to provide feedback to the department on all aspects of the undergraduate academic experience,

More information