Examples and Applications of Binary Search

Similar documents
Homework 1 Solutions MA 522 Fall 2017

The isoperimetric problem on the hypercube

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Lecture 5. Counting Sort / Radix Sort

Algorithm Design Techniques. Divide and conquer Problem

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

CMPT 125 Assignment 2 Solutions

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

Analysis of Algorithms

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

A graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))

Lecture 1: Introduction and Strassen s Algorithm

Alpha Individual Solutions MAΘ National Convention 2013

Module 8-7: Pascal s Triangle and the Binomial Theorem

15-859E: Advanced Algorithms CMU, Spring 2015 Lecture #2: Randomized MST and MST Verification January 14, 2015

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Ch 9.3 Geometric Sequences and Series Lessons

Σ P(i) ( depth T (K i ) + 1),

Parabolic Path to a Best Best-Fit Line:

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Algorithm. Counting Sort Analysis of Algorithms

6.854J / J Advanced Algorithms Fall 2008

1.2 Binomial Coefficients and Subsets

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Lecture 6. Lecturer: Ronitt Rubinfeld Scribes: Chen Ziv, Eliav Buchnik, Ophir Arie, Jonathan Gradstein

Protected points in ordered trees

Exercise 6 (Week 42) For the foreign students only.

How do we evaluate algorithms?

Lecture 28: Data Link Layer

Data Structures and Algorithms. Analysis of Algorithms

Data Structures Week #9. Sorting

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

CSE 2320 Notes 8: Sorting. (Last updated 10/3/18 7:16 PM) Idea: Take an unsorted (sub)array and partition into two subarrays such that.

EE123 Digital Signal Processing

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

ECE4050 Data Structures and Algorithms. Lecture 6: Searching

CSE 417: Algorithms and Computational Complexity

. Written in factored form it is easy to see that the roots are 2, 2, i,

Computational Geometry

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

27 Refraction, Dispersion, Internal Reflection

CS473-Algorithms I. Lecture 2. Asymptotic Notation. CS 473 Lecture 2 1

DATA STRUCTURES. amortized analysis binomial heaps Fibonacci heaps union-find. Data structures. Appetizer. Appetizer

Big-O Analysis. Asymptotics

Priority Queues. Binary Heaps

Data Structures and Algorithms Part 1.4

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

Data Structures Week #5. Trees (Ağaçlar)

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

Practical Session 2 Constants Don t Matter!!!

1 Graph Sparsfication

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

Lecture 7 7 Refraction and Snell s Law Reading Assignment: Read Kipnis Chapter 4 Refraction of Light, Section III, IV

EE University of Minnesota. Midterm Exam #1. Prof. Matthew O'Keefe TA: Eric Seppanen. Department of Electrical and Computer Engineering

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

Combination Labelings Of Graphs

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

Lecture 2: Spectra of Graphs

NTH, GEOMETRIC, AND TELESCOPING TEST

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

Sorting 9/15/2009. Sorting Problem. Insertion Sort: Soundness. Insertion Sort. Insertion Sort: Running Time. Insertion Sort: Soundness

Numerical Methods Lecture 6 - Curve Fitting Techniques

Array Applications. Sorting. Want to put the contents of an array in order. Selection Sort Bubble Sort Insertion Sort. Quicksort Quickersort

condition w i B i S maximum u i

Random Graphs and Complex Networks T

2. ALGORITHM ANALYSIS

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

Intro to Scientific Computing: Solutions

5.3 Recursive definitions and structural induction

CHAPTER IV: GRAPH THEORY. Section 1: Introduction to Graphs

The Adjacency Matrix and The nth Eigenvalue

Mathematical Stat I: solutions of homework 1

Chapter 3 Classification of FFT Processor Algorithms

Recursive Procedures. How can you model the relationship between consecutive terms of a sequence?

Chapter 4 The Datapath

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Ones Assignment Method for Solving Traveling Salesman Problem

Weston Anniversary Fund

Graphs. Minimum Spanning Trees. Slides by Rose Hoberman (CMU)

Greedy Algorithms. Interval Scheduling. Greedy Algorithms. Interval scheduling. Greedy Algorithms. Interval Scheduling

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

Python Programming: An Introduction to Computer Science

Big-O Analysis. Asymptotics

BST Sequence of Operations

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

Lower Bounds for Sorting

Perhaps the method will give that for every e > U f() > p - 3/+e There is o o-trivial upper boud for f() ad ot eve f() < Z - e. seems to be kow, where

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Minimum Spanning Trees

Transcription:

Toy Gog ITEE Uiersity of Queeslad

I the secod lecture last week we studied the biary search algorithm that soles the problem of determiig if a particular alue appears i a sorted list of iteger or ot. We proed that the worst-case ruig time of the algorithm uder the RAM model that we hae defied is 2 + 6 log 2, where (the legth of the sorted sequece) is the problem size. Today we will look at some further examples of how the biary search algorithm rus to help us uderstad its behaiour.

Example 1 Suppose we hae the followig iput set, where = 8 ad we are tryig to fid the alue 7. 8 7 2 3 5 7 11 13 17 19

Example 1 We begi by iitialisig left to be 1 ad right to (i this case 8). 8 7 L M R 1 8 2 3 5 7 11 13 17 19

Example 1 Sice the alue of right is strictly greater tha the alue of left, we proceed by computig mid. 8 7 L M R 1 4 8 2 3 5 7 11 13 17 19

Example 1 We the do a compariso of the alue we re lookig for with the alue i the sorted sequeced idexed by mid. We get lucky i this case ad fid that they are actually equal, meaig we ca stop here ad say that the alue does appear i the sorted sequece. 8 7 L M R 1 4 8 2 3 5 7 11 13 17 19

The preious example illustrates that the algorithm may termiate i far less time (if we get lucky) tha 2 + 6 log 2. This worst-case ruig time that we proed gies us a guaratee o how fast our algorithm rus, ad is idepedet of luck. Let s look at aother example.

Example 2 I this example, we keep the same sorted sequece but look for the alue 11 istead. L ad R get iitialised as before, M gets computed ad we perform the compariso to fid that is greater tha the Mth term i the sequece. 8 11 L M R 1 4 8 2 3 5 7 11 13 17 19

Example 2 The meas that what we are lookig for is i the right half of the sorted sequece, hece we set L to be M + 1 (ad coceptually discard the left half of the sequece). We the recompute M ad do aother compariso, this time fidig that is less tha the alue at M. 8 11 L M R 5 6 8 11 13 17 19

Example 2 So ow we adjust R (ad throw away the right half) to be M 1, ad fid that L ad R hae coerged, meaig there s oly a sigle alue for us to check. Ideed we fid that it is the alue we are lookig for, therefore the output i this case is yes. 8 11 L M R 5 5 11

Example 3 For this last example, we will look at a case where the alue we are lookig for does ot appear i the sorted sequece. Here the first compariso tells us that would hae to be i the right half of the sequece (if it was to appear at all). 8 15 L M R 1 4 8 2 3 5 7 11 13 17 19

Example 3 The secod compariso agais says that must i the right half. 8 L M 15 5 6 R 8 11 13 17 19

Example 3 The third compariso tells us that must be to the left of the highlighted alue of 17, but we see that there are t ay alues to the left of 17... 8 L M 15 7 7 R 8 17 19

Example 3 Ad so we arrie at the base case where we o loger hae L R, which tells us that what we are lookig for does ot appear i the sequece. 8 L M R 15 7 6

The Sum of Two Itegers Problem Now let s look at how biary search ca be applied. Suppose we hae the followig problem: Problem Iput: There is a sequece of positie itegers i strictly icreasig order i memory at the cells umbered from 1 up to. The alue has bee placed i Register 1, ad the a positie iteger has bee placed i Register 2. Goal: Determie whether if there exist two itegers x ad y (ot ecessarily distict) i the sorted sequece such that x + y =.

Example A yes -iput with = 12 12 30 2 3 5 7 11 13 17 19 23 29 31 37 A o -iput with = 12 12 29 2 3 5 7 11 13 17 19 23 29 31 37

A First Attempt A aïe algorithm to sole this problem is to eumerate all possible pairs i the sorted sequece ad check if they sum to. Gie a sequece of legth, there are: 1 + 2 + + = ( + 1) 2 such pairs. This is o the order of 2, but ca we do better tha this? Hit: Take adatage of the fact that the gie sequece is sorted!

Biary Search The Aswer If we rearraged the equatio ad put it i the form y = x, we ca rephrase the problem i terms of whether if such a y exists i the sequece for eery x i the sequece. The idea is the to let x ru oer the sequece, compute y as x ad use biary search to see if y exists i the sequece.

The Repeated Biary Search Algorithm i Pseudocode 1. Let be register 1 ad be register 2 2. register i 1, register oe 1 3. while i 4. read ito register x the memory cell at address i 5. y x 6. if BiarySearch(y) = yes 7. retur yes 7. i i + oe (effectiely icreasig i by 1) 8. retur o

Ruig Time I the worst case (this happes whe the output is o ), the algorithm eeds to ru biary search times. A precise cout yields a time of f () = 3 + 7 + 6 log 2. This is a improemet oer the aïe algorithm we cosidered preiously. The story does t ed there howeer... because we ca do ee better tha this!

A Ee Better Algorithm I fact the sortedess of our sequece of itegers meas that we ca fid the solutio by cosiderig each term oly oce! The idea is as follows: 12 29 2 3 5 7 11 13 17 19 23 29 31 37 Coceptually we will hae two poiters (as highlighed i blue), ad they will begi by poitig at the start ad the ed respectiely. If we summed the two umbers beig poited to, we get 39, which is greater tha the desired alue of 29.

A Ee Better Algorithm 12 29 2 3 5 7 11 13 17 19 23 29 31 37 This tells us that: 37 will eer appear i a alid solutio, because 2 is the smallest term i the sequece ad the sum is already greater tha the desired alue; ad i order to get a solutio, we should moe the right poiter towards the left, sice this will decrease the oerall alue of the sum.

A Ee Better Algorithm After fidig that 31 ad 29 are also too large, we arrie at the followig: 12 29 2 3 5 7 11 13 17 19 23 The sum is ow too small, ad what this tells us is that 2 eer appears i a solutio because 23 is the largest alue that we hae, ad that the solutio is still too small meas that 2 plus ay other umber i the sequece would also be too small. This meas that we should moe the left poiter towards the right to icrease our estimate.

A Ee Better Algorithm Oe shall fid after moig the left poiter that 3 ad 5 are also too small, arriig at: 12 29 7 11 13 17 19 23 Ad ow it s too big ad we eed to moe the right poiter, etc.

The Mai Idea Essetially, if we thik of x as the elemet beig poited to by the left poiter ad y as the elemet beig poited to by the right poiter: if x + y =, we re doe; if x + y >, we eed to make the sum smaller, so moe y towards the left; ad if x + y <, we eed to make the sum bigger, so moe x towards the right.

Pseudocode 1. let be register 1, ad be register 2 2. register left 1, right 3. while left right 4. read ito register x the memory cell at address left 5. read ito register y the memory cell at address right 6. if x + y = the 7. retur yes 8. else if x + y > the 9. right right 1 10. else 11. left left + 1 12. retur o This algorithm has a worst-case ruig time of 5 + 4.

Recap I this week s tutorial, we reiewed the biary search algorithm ad looked at a problem that ca be soled by repeated applicatio of biary search (although the best algorithm tured out to be ee cleerer). You are ecouraged to ru this algorithm o some iput sets ad coice yourself that it actually gies the correct result.