BINARY SEARCH CS16: Introduction to Data Structures & Algorithms Thursday February 12, 2015 1.

Slides:



Advertisements
Similar presentations
Introduction to Computer Science Theory
Advertisements

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
CSE 373: Data Structures and Algorithms Lecture 5: Math Review/Asymptotic Analysis III 1.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Divide and Conquer Strategy
© 2004 Goodrich, Tamassia QuickSort1 Quick-Sort     29  9.
Search and Recursion CS221 – 2/23/09. List Search Algorithms Linear Search: Simple search through unsorted data. Time complexity = O(n) Binary Search:
CSE 326 Analyzing Recursion David Kaplan Dept of Computer Science & Engineering Autumn 2001.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Divide-and-Conquer1 7 2  9 4   2  2 79  4   72  29  94  4 Modified by: Daniel Gomez-Prado, University of Massachusetts Amherst.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
Data Structures Review Session 1
CSC 2300 Data Structures & Algorithms January 30, 2007 Chapter 2. Algorithm Analysis.
Data Structure Algorithm Analysis TA: Abbas Sarraf
Searching1 Searching The truth is out there.... searching2 Serial Search Brute force algorithm: examine each array item sequentially until either: –the.
Analysis of Algorithms COMP171 Fall Analysis of Algorithms / Slide 2 Introduction * What is Algorithm? n a clearly specified set of simple instructions.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search -Reading p
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
analysis, plug ‘n’ chug, & induction
CS Discrete Mathematical Structures Mehdi Ghayoumi MSB rm 132 Ofc hr: Thur, 9:30-11:30a.
Analysis of Algorithms
Lecture 12. Searching Algorithms and its analysis 1.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
1 Searching and Sorting Linear Search Binary Search.
Searching CS 105 See Section 14.6 of Horstmann text.
Searching. RHS – SOC 2 Searching A magic trick: –Let a person secretly choose a random number between 1 and 1000 –Announce that you can guess the number.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Searching. Linear (Sequential) Search Search an array or list by checking items one at a time. Linear search is usually very simple to implement, and.
Analysis of Algorithms These slides are a modified version of the slides used by Prof. Eltabakh in his offering of CS2223 in D term 2013.
Growth of Functions. Asymptotic Analysis for Algorithms T(n) = the maximum number of steps taken by an algorithm for any input of size n (worst-case runtime)
CSC 211 Data Structures Lecture 13
1 CSC 427: Data Structures and Algorithm Analysis Fall 2008 Algorithm analysis, searching and sorting  best vs. average vs. worst case analysis  big-Oh.
Lecture 5 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
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.
CS 61B Data Structures and Programming Methodology July 21, 2008 David Sun.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Recurrences David Kauchak cs161 Summer Administrative Algorithms graded on efficiency! Be specific about the run times (e.g. log bases) Reminder:
1 Algorithms  Algorithms are simply a list of steps required to solve some particular problem  They are designed as abstractions of processes carried.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS212: DATASTRUCTURES Lecture 3: Searching 1. Lecture Contents  searching  Sequential search algorithm.  Binary search algorithm. 2.
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 CS 110: Data Structures and Algorithms First Semester,
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Algorithmic Foundations COMP108 COMP108 Algorithmic Foundations Algorithm efficiency Prudence Wong
Recursion Version 1.0.
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
Analysis of Algorithms
Searching Given a collection and an element (key) to find… Output
COMP108 Algorithmic Foundations Algorithm efficiency
Chapter 9: Searching, Sorting, and Algorithm Analysis
CS 3343: Analysis of Algorithms
Introduction to the Design and Analysis of Algorithms
Searching CSCE 121 J. Michael Moore.
Merge Sort Merge sort is a recursive algorithm for sorting that decomposes the large problem.
CS 3343: Analysis of Algorithms
Algorithm Analysis (not included in any exams!)
CSc 110, Spring 2017 Lecture 39: searching.
Divide-and-Conquer 7 2  9 4   2   4   7
CSE 373 Data Structures and Algorithms
And now for something completely different . . .
Divide-and-Conquer 7 2  9 4   2   4   7
Divide-and-Conquer 7 2  9 4   2   4   7
Presentation transcript:

BINARY SEARCH CS16: Introduction to Data Structures & Algorithms Thursday February 12,

Outline 1) Binary Search 2) Binary Search Pseudocode 3) Analysis of Binary Search 4) In-Place Binary Search 5) Iterative Binary Search Thursday February 12,

The Problem Determine whether an item, x, is in a sorted array Obvious solution: iterate through the entire array and check each element to see if it’s the one we’re searching for This solution is O(n). Can we do better? Let’s use the fact that the array is sorted! If we’re looking for the item x, we can stop searching as soon as we find an item y > x, because we know x can’t come after y in the array But what if we’re looking for 25 in the example above? Worst case still O(n). Boooo. Thursday February 12, e.g. is 5 in this array?

Binary Search What if we compared x to the middle element of the array, mid? If mid == x, then we found x! If mid < x, then we know x must be in the second half of the array, if it’s there at all If mid > x, then we know x must be in the first half of the array, if it’s there at all Important observation: No matter what, we can eliminate half of the array We then end up with the same problem, but half the size! Thursday February 12, mid WOAH WE SHOULD DO IT AGAIN

Binary Search Simulation Thursday February 12, Goal: Find 5 because 5 < because 5 > 4 7 because 5 < 8 Since 7 ≠ 5, we can conclude that 5 is NOT in the array. And it only took us four comparisons!

Binary Search: First Analysis For an array of size n, how many comparisons do we need to make to determine if x is in the array? (worst case) After each comparison, the array size is cut in half So how many times must we divide n by 2, before we get an array of size 1? log 2 n! So binary search should be O(log n), right??? Let’s try out some pseudocode and see… Thursday February 12,

Binary Search Pseudocode Thursday February 12, function binarySearch(A, x): // Input: A, a sorted array // x, the item to find // Output: true if x is in A, else false if A.size == 0: return false if A.size == 1: return A[0] == x mid = A.size / 2 if A[mid] == x: return true if A[mid] < x: return binarySearch(A[mid end], x) if A[mid] > x: return binarySearch(A[0...mid – 1], x)

Binary Search Analyzed Since each recursive call cuts the problem size in half, the recurrence relation for binary search looks like: T(1) = c T(n) = T(n/2) + f(n) Where f(n) is the amount of work done at each level of recursion Thursday February 12,

Binary Search Analyzed (2) Thursday February 12, Haaang on. What is this sketchy business here?? In order to pass a smaller array to the recursive call, we’re making a new array and copying over half the contents! This step’s O(n), kid… function binarySearch(A, x): if A.size == 0: O(1) return false O(1) if A.size == 1: O(1) return A[0] == x O(1) mid = A.size / 2 O(1) if A[mid] == x: O(1) return true O(1) if A[mid] < x: O(1) return binarySearch(A[mid end], x) if A[mid] > x: O(1) return binarySearch(A[0...mid – 1], x) (base case 1) (base case 2)

Binary Search Analyzed (3) Now that we know f(n) is O(n), we can solve our recurrence relation using plug ‘n’ chug Therefore, T(n) is O(n + log n), which is O(n). That’s just as bad as iterating through the whole array! Thursday February 12, this sum converges to 2n, as n increases f(n), a linear function of n

What went wrong? In our initial simulation of binary search, we found that it took only O(log n) comparisons to solve the problem But when it came to implementing the algorithm, copying half the array ended up costing us too much at each step! The runtime went back up to O(n) This is a very common pitfall when trying to implement efficient algorithms. Sometimes taking the most straightforward approach is not enough to achieve the fast runtime you hope for In the case of binary search, this means we need to implement the algorithm in-place. In other words, we can only use the array that was given to us as input. No copying allowed! Thursday February 12,

In-Place Binary Search Thursday February 12, function binarySearch(A, lo, hi, x): // Input: A – a sorted array // lo, hi – two valid indices of the array // x – the item to find // Output: true if x is in the array between lo and hi, inclusive if lo >= hi: return A[lo] == x mid = (lo + hi) / 2 if A[mid] == x: return true if A[mid] < x: return binarySearch(A, mid + 1, hi, x) if A[mid] > x: return binarySearch(A, lo, mid – 1, x)

In-Place Binary Search (2) Now it’s clear that our binary search only performs a constant number of operations at each iteration The recurrence relation becomes: T(n) = T(n/2) + c 1 Plugging in, we get: T(1) = c 0 T(2) = T(1) + c 1 = c 0 + c 1 T(4) = T(2) + c 1 = c 0 + 2c 1 T(8) = T(4) + c 1 = c 0 + 3c 1 T(2 k ) = c 0 + kc 1 If we let n = 2 k, then: T(n) = c 0 + (log 2 n)c 1 So our in-place algorithm is O(log n)! Yay! Thursday February 12,

In-Place Binary Search: Iterative Thursday February 12, function binarySearch(A, x): // Input: A – a sorted array // x – the item to find // Output: true if x is in the array lo = 0 hi = A.size - 1 while lo < hi: mid = (lo + hi) / 2 if A[mid] == x: return true if A[mid] < x: lo = mid + 1 if A[mid] > x: hi = mid – 1 return A[lo] == x Remember: Any recursive algorithm can be implemented iteratively!