Linear vs Binary Search COP 3502. What is recursion? // Pre-conditions: exponent is >= to 0 // Post-conditions: returns base exponent int Power(int base,

Slides:



Advertisements
Similar presentations
Recursion.
Advertisements

Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Recursion.
Topic 14 Searching and Simple Sorts "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The.
Tree Recursion Traditional Approach. Tree Recursion Consider the Fibonacci Number Sequence: Time: , 1, 1, 2, 3, 5, 8, 13, 21,... /
Introduction to Algorithms Quicksort
Starting Out with Java: From Control Structures through Objects
Introduction to Recursion and Recursive Algorithms
12-Apr-15 Analysis of Algorithms. 2 Time and space To analyze an algorithm means: developing a formula for predicting how fast an algorithm is, based.
MATH 224 – Discrete Mathematics
Practice Quiz Question
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Factorial Recursion stack Binary Search Towers of Hanoi
Computer Science 112 Fundamentals of Programming II Finding Faster Algorithms.
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Search and Recursion CS221 – 2/23/09. List Search Algorithms Linear Search: Simple search through unsorted data. Time complexity = O(n) Binary Search:
Search and Recursion pt. 2 CS221 – 2/25/09. How to Implement Binary Search Take a sorted data-set to search and a key to search for Start at the mid-point.
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.
Binary Search Visualization i j.
Recursion. Binary search example postponed to end of lecture.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Recursion.
1 Section 3.5 Recursive Algorithms. 2 Sometimes we can reduce solution of problem to solution of same problem with set of smaller input values When such.
CSC 2300 Data Structures & Algorithms January 30, 2007 Chapter 2. Algorithm Analysis.
Elementary Data Structures and Algorithms
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search -Reading p
COMP s1 Computing 2 Complexity
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
CPT: Search/ Computer Programming Techniques Semester 1, 1998 Objectives of these slides: –to discuss searching: its implementation,
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Analysis of Algorithms
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
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.
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 Linear Search Binary Search.
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.
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
Searching and Sorting Topics Linear and Binary Searches Selection Sort Bubble Sort.
Search algorithms for vectors Jordi Cortadella Department of Computer Science.
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.
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.
Sorting.
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.
Week 12 - Friday.  What did we talk about last time?  Finished hunters and prey  Class variables  Constants  Class constants  Started Big Oh notation.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Visual C++ Programming: Concepts and Projects Chapter 8A: Binary Search (Concepts)
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.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Ramamurthy Recursion: The Mirrors B. Ramamurthy CS114A,B.
Recursion COMP x1 Sedgewick Chapter 5. Recursive Functions problems can sometimes be expressed in terms of a simpler instance of the same problem.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
Algorithm Analysis with Big Oh ©Rick Mercer. Two Searching Algorithms  Objectives  Analyze the efficiency of algorithms  Analyze two classic algorithms.
BINARY SEARCH CS16: Introduction to Data Structures & Algorithms Thursday February 12,
Searching/Sorting. Searching Searching is the problem of Looking up a specific item within a collection of items. Searching is the problem of Looking.
Towers of Hanoi Move n (4) disks from pole A to pole C
Sorting by Tammy Bailey
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Algorithm design and Analysis
Linear Search Binary Search Tree
Searching.
Presentation transcript:

Linear vs Binary Search COP 3502

What is recursion? // Pre-conditions: exponent is >= to 0 // Post-conditions: returns base exponent int Power(int base, int exponent) { if (exponent == 0) return 1; else return (base*Power(base, exponent – 1); } Power(5,2) :return 5 * Power(5,1) return 5 * Power(5,0)Power(5,1) : return 1Power(5,0) : Stack trace back to the original function call 1 5 * 1 = 5 5* 5 = 25  To convince you that this works, let’s look at an example:  Power(5,2): STACK

Recursion  Why use recursion?  Some solutions are naturally recursive.  In these cases there might be less code for a recursive solution, and it might be easier to read and understand.  Why NOT user recursion?  Every problem that can be solved with recursion can be solved iteratively.  Recursive calls take up memory and CPU time  Exponential Complexity – calling the Fib function uses 2 n function calls.  Consider time and space complexity.

Recursion Example  Let’s do another example problem – Fibonacci Sequence  1, 1, 2, 3, 5, 8, 13, 21, …  Let’s create a function int Fib(int n)  we return the nth Fibonacci number  Fib(1) = 1, Fib(2) = 1, Fib(3) = 2, Fib(4) = 3, Fib(5) = 5, …  What would our base (or stopping) cases be?

Fibonacci  1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …  Base (stopping) cases:  Fib(1) = 1  Fib(2) = 1,  Then for the rest of the cases: Fib(n) = ?  Fib(n) = Fib(n-1) + Fib(n-2), for n>2  So Fib(9) = ?  Fib(8) + Fib(7) =

Recursion - Fibonacci  See if we can program the Fibonacci example…

Recursion - Fibonacci  Let’s say we called Fibo(5), we can visualize the calls to Fibo on the stack as a tree: Fibo(5) Fibo(4)Fibo(3) Fibo(2) Fibo(1) Fibo(2)Fibo(1)

Recursion - Fibonacci  Let’s say we called Fibo(5), we can visualize the calls to Fibo on the stack as a tree: Fibo(5) Fibo(4)Fibo(3) Fibo(2) Fibo(1) Fibo(2)Fibo(1)

Recursion - Fibonacci  Let’s say we called Fibo(5), we can visualize the calls to Fibo on the stack as a tree: Fibo(5) Fibo(4)Fibo(3) Fibo(2) Fibo(1) Fibo(2)Fibo(1) 3+2=5 2+1=3 1+1=

Linear Search  In C Programming, we looked at the problem of finding a specified value in an array.  The basic strategy was:  Look at each value in the array and compare to x – If we see that value, return true – else keep looking – If we’re done looking through the array and still haven’t found it, return false. int search(int array[], int len, int value) { int i; for (i = 0; i < len; i++) { if (array[i] == value) return 1; } return 0; }

Linear Search  For an unsorted array, this algorithm is optimal.  There’s no way you can definitively say that a value isn’t in the array unless you look at every single spot.  But we might ask the question, could we find an item in an array faster if it were already sorted? int search(int array[], int len, int value) { int i; for (i = 0; i < len; i++) { if (array[i] == value) return 1; } return 0; }

Binary Search  Consider the game you probably played when you were little:  I have a secret number in between 1 and 100, make a guess and I’ll tell you whether your guess is too high or too low.  Then you guess again, and continue guessing until you guess right.  What would a good strategy for this game be?

Binary Search  If you divide your search space in half each time,  you won’t run the risk of searching ¾ of the list each time.  For instance, if you pick 75 for your number, and you get the response “too high”,  Then your number is anywhere from 1-74…  So generally the best strategy is:  Always guess the number that is halfway between the lowest possible value in your search range and the highest possible value in your search range.

Binary Search  How can we adapt this strategy to work for search for a given value in an array?  Given the array:  Search for 19  Where is halfway in between?  One guess would be (118+2) / 2 = 60  But 60 isn’t in the list and the closest value to 60 is 41 almost at the end of the list.  We want the middle INDEX of the array.  In this case: The lowest index is 0, the highest is 8, so the middle index is 4! Index Value MIDMID MIDMID LOWLOW LOWLOW HIHI HIHI

Binary Search  Searching for 19:  Now we ask,  Is 19 greater than, or less than, the number at index 4?  It is Less than, so now we only want to search from index 0 to index 3. Index Value MIDMID MIDMID

Binary Search  Searching for 19:  The middle of 0 and 3 is 1 ( since (3+0)/2 = 1)  So we look at array[1]  And ask is 19 greater than or less than 6?  Since it’s greater than 6, we next search halfway between 2 and 3, which is (2+3)/2 = 2  At index 2, we find 19! Index Value Don’t care about these anymore! MIDMID MIDMID LOWLOW LOWLOW HIHI HIHI LOWLOW LOWLOW MIDMID MIDMID

Binary Search Index0………n/2………n Valuex1x1 x2x2 x…x… x…x… x…x… x…x… x…x… x…x… xnxn MIDMID MIDMID LOWLOW LOWLOW HIHI HIHI int binsearch(int array[], int n, int value) { int low = 0, high = n – 1; while (low <= high) { int mid = (low + high)/2; if (value < array[mid]) high = mid – 1; else if (value > array[mid]) low = mid + 1; else return 1; } return 0; }

Efficiency of Binary Search  Now, let’s analyze how many comparisons (guesses) are necessary when running this algorithm on an array of n items.  First, let’s try n = 100:  After 1 guess, we have 50 items left,  After 2 guesses, we have 25 items left,  After 3 guesses, we have 12 items left,  After 4 guesses, we have 6 items left,  After 5 guesses, we have 3 items left,  After 6 guesses, we have 1 item left,  After 7 guesses, we have 0 items left.  The reason we have to list that last iteration is because the number of items left represent the number of other possible values to search.  We need to reduce this number to 0! Also note that when n is odd, such as when n = 25, We search the middle element #13, There are 12 elements smaller than it and 12 larger, So the number of items left is slightly less than 1/2.

Efficiency of Binary Search

 Let’s look at a comparison of a linear search to a logarithmic search: nlog n

Recursion COP 3502

Recursive Binary Search  The iterative code is not the easiest to read, if we look at the recursive code  It’s MUCH easier to read and understand int binsearch(int *values, int low, int high, int searchVal) { int mid; if (!terminating condition){ } return 0; }

Recursive Binary Search int binsearch(int *values, int low, int high, int searchVal) { int mid; if (!terminating condition){ } return 0; }  We need a stopping case:  We have to STOP the recursion at some point  Stopping cases: 1.We found the number! 2.Or we have reduced our search range to nothing – the number wasn’t found   ?? The search range would be empty when low > high int binsearch(int *values, int low, int high, int searchVal) { int mid; if (low <= high){ mid = (low+high)/2; if (searchVal == values[mid]) return 1; } return 0; } int binsearch(int *values, int low, int high, int searchVal) { int mid; if (low <= high){ mid = (low+high)/2; if (searchVal == values[mid]) return 1; // Otherwise recursively search here } return 0; } int binsearch(int *values, int low, int high, int searchVal) { int mid; if (low <= high){ mid = (low+high)/2; if (searchVal == values[mid]) return 1; else if (searchVal > values[mid]) // Do something else else // Do something } return 0; }

Recursive Binary Search  What are our recursive calls going to be?  We need to change what low and high are  So we get the following: int binsearch(int *values, int low, int high, int searchVal) { int mid; if (low <= high){ mid = (low+high)/2; if (searchVal == values[mid]) return 1; else if (searchVal > values[mid]) return binsearch(values, mid+1, high, searchval) else return binsearch(values, low, mid-1, searchval); } return 0; } int binsearch(int *values, int low, int high, int searchVal) { int mid; if (low <= high){ mid = (low+high)/2; if (searchVal == values[mid]) return 1; else if (searchVal > values[mid]) // Do something else else // Do something } return 0; }

Recursive Binary Search  Binary Search Code summary (using recursion):  If the value is found,  return 1  Otherwise  if (searchVal > values[mid]) – Recursively call binsearch to the right  else if (searchVal < values[mid]) – Recursively call binsearch to the left  If low is ever greater than high  The value is not in the array return 0

Practice Problem  Write a recursive function that:  Takes in 2 non-negative integers  Returns the product  Does NOT use multiplication to get the answer  So if the parameters are 6 and 4  We get 24  Not using multiplication, we would have to do

Practice Problem  Write a recursive function that:  Takes in 2 non-negative integers  Returns the product  Does NOT use multiplication to get the answer int Multiply(int first, int second) { if (( second == 0 ) || ( first = 0)) return 0; else return (first + Multiply(first, second – 1)); }