Recursion Riley Chapter 14 Sections 14.1 – 14.5 (14.6 optional)

Slides:



Advertisements
Similar presentations
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Advertisements

21/3/00SEM107- Kamin & ReddyClass 15 - Recursive Sorting - 1 Class 15 - Recursive sorting methods r Processing arrays by recursion r Divide-and-conquer.
DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
Introduction to Algorithms Chapter 7: Quick Sort.
QuickSort The content for these slides was originally created by Gerard Harrison. Ported to C# by Mike Panitz.
Data Structures and Algorithms PLSD210 Sorting. Card players all know how to sort … First card is already sorted With all the rest, ¶Scan back from the.
CS 162 Intro to Programming II Quick Sort 1. Quicksort Maybe the most commonly used algorithm Quicksort is also a divide and conquer algorithm Advantage.
Quick Sort. 2 Divide: Pick any element p as the pivot, e.g, the first element Partition the remaining elements into FirstPart, which contains all elements.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. Sorting III 1 An Introduction to Sorting.
Quicksort.
Unit 061 Quick Sort csc326 Information Structures Spring 2009.
CS2420: Lecture 11 Vladimir Kulyukin Computer Science Department Utah State University.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Computer Science Searching & Sorting.
P-1 University of Washington Computer Programming I Lecture 15: Linear & Binary Search ©2000 UW CSE.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Searching Course Lecture Slides 28 May 2010 “ Some things Man was never.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
Sort Algorithms.
1 CSE 373 Sorting 3: Merge Sort, Quick Sort reading: Weiss Ch. 7 slides created by Marty Stepp
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.
Chapter 6 Recursion. Solving simple problems Iteration can be replaced by a recursive function Recursion is the process of a function calling itself.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
The Sorting Methods Lecture Notes 10. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. –
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
QuickSort. Yet another sorting algorithm! Usually faster than other algorithms on average, although worst-case is O(n 2 ) Divide-and-conquer: –Divide:
Mudasser Naseer 1 3/4/2016 CSC 201: Design and Analysis of Algorithms Lecture # 6 Bubblesort Quicksort.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CSE / ENGR 142 Programming I
Prof. U V THETE Dept. of Computer Science YMA
Sorts, CompareTo Method and Strings
Sorting Mr. Jacobs.
Sort & Search Algorithms
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Lecture 14 Searching and Sorting Richard Gesick.
Quick Sort and Merge Sort
Data Structures in Java with JUnit ©Rick Mercer
Quicksort
Sorting and Searching Sudeshna Sarkar 7th Feb 2017.
Chapter 7 Sorting Spring 14
Quicksort "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 Sorting Hat, Harry Potter.
Teach A level Computing: Algorithms and Data Structures
Data Structures and Algorithms
CSC 413/513: Intro to Algorithms
Quicksort 1.
Department of Computer and Information Science, School of Science, IUPUI Quicksort Dale Roberts, Lecturer Computer Science, IUPUI
Chapter 4: Divide and Conquer
CO 303 Algorithm Analysis And Design Quicksort
Quicksort analysis Bubble sort
CSC215 Lecture Algorithms.
Unit-2 Divide and Conquer
Lecture 11 Searching and Sorting Richard Gesick.
Sorting … and Insertion Sort.
Searching and Sorting 1-D Arrays
Sub-Quadratic Sorting Algorithms
slides adapted from Marty Stepp
Chapter 4.
CSE 326: Data Structures Sorting
Sorting.
CS 3343: Analysis of Algorithms
Quicksort.
CSE 373 Data Structures and Algorithms
Algorithms: Design and Analysis
Data Structures & Algorithms
Quicksort.
CSE 332: Sorting II Spring 2016.
Quicksort.
Presentation transcript:

Recursion Riley Chapter 14 Sections 14.1 – 14.5 (14.6 optional)

Factorial using repetition… 0! is 1 1! is 1 2! is 1 * 2 3! is 1 * 2 * 3 . . . Factorial using repetition… method name int factorial ( int n ) { int product, i ; product = 1 ; for ( i = n ; i > 1 ; i-- ) { product = product * i ; } return (product) ; Formal parameter local variables return type & value

Review: Method Basics Tracing recursive methods is easy if you remember method basics : Formal parameters and variables declared in a method are local to it… Allocated (created) on method entry De-allocated (destroyed) on method return Formal parameters initialized by copying value of actual parameter.

Factorial via Recursion /* 0! = 1! = 1; for n > 1, n! = n(n-1)! */ int factorial (int n) { int t; if (n <= 1) t = 1; else t = n * factorial(n - 1); return t; } Basis clause or “simple case” Recursive clause or general case -- “making progress” 0! is 1 1! is 1 n! is n * (n-1)!, for n>1 E.g.: 3! =3 * 2! = 3 * 2 * 1! = 3 * 2 * 1

Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24

Factorial Trace n t The only communication between methods is via parameters of the method call and return values. n t n t Notice that each stack frame (or “method activation” as Riley calls it) has its own separate set of local variables. The only communication between the separate method activations is via parameters of the method call and return values. Every time a method is called (an “activation”), a stack frame is created for its local variables. Each activation has its own set! n t

Iteration vs Recursion Turns out any iterative algorithm can be reworked to use recursion instead. Some algorithms are more naturally written with recursion than others recursion is often less efficient There are even programming languages where recursion is the only choice!

Fibonacci (slightly different from the text) int jthFib (int j) { if (j <= 0) return 0; /* a "basis clause" or "base case" */ else if (j == 1) return 1; /* another base case */ else /*"recursive clause" or general case ("making progress"*/ return jthFib (j-1) + jthFib (j-2); } Recursive Fibonacci is elegant and compact, but not very efficient.

Searching Searching = looking for something Like sorting, searching is a common and useful operation Searching an array is very common Goal: determine if a particular value is in the array If the array is unsorted: start at the beginning and look at each element to see if it matches

There is a better way "Binary search" works if the array is sorted 1. Look for the target in the middle. 2. If you don't find it, you can throw away half of the array, and repeat the process with the other half. Turns out you only need about log2(size) comparisons

Is it worth the trouble? Suppose you had 1000 elements Ordinary search would require 500 comparisons on average Try a Binary search

Binary Search Try a Binary search after 1st compare, throw away half, leaving 500 elements to be searched. after 2nd compare, throw away half, leaving 250. Then 125, 63, 32, 16, 8, 4, 2, 1 are left. After at most 10 steps, you're done! What if you had 1,000,000 elements??

Recursive Binary Search /*Precondition: the array is sorted */ /*Returns -1 if target not found; returns index of target if found */ int search (double[] a, double target, int low, int high) { int mid = (low+high)/2; if (target == a[mid]) return mid; /* found! */ if (low >= high) return -1; /* not found */ if (target < a[mid]) return search (a, target, low, mid-1); else return search (a, target, mid+1, high); }

Kick-off Each time search is called, it searches only a part of the array The first time it's called, tell it to search everything public int testSearch( double target ) { final int snum = 8; double grades[ ] = {0.0, 0.7, 2.0, 2.8, 3.1, 3.3, 3.9, 4.0}; return( search (grades, target, 0, snum-1) ); }

i grades[i] 0 0.0 1 0.7 2 2.0 3 2.8 4 3.1 5 3.3 6 3.9 7 4.0 snum is 8 first call: search (grades, 3.9, 0, 7)

Is Binary Search the Last Word? For sorted arrays, yes. Real-world data is often messier, unfortunately In games: search for the best move is important Chess: how many moves are possible at each stage of a game?? Deep Blue has special hardware

Quicksort To sort a set S: Choose a ‘pivot’ element x from S. Construct S1, the elements less than x Construct S2, the elements greater than x Sort the sets S1 and S2 Output the sorted S1, then x, then the sorted S2

Quicksort Example 12, 15, 18, 8, 2, 19, 5, 13, 16, 9, 6, 1 8, 2, 5, 9, 6, 1, 12, 15, 18, 19, 13, 16 2, 5, 6, 1, 8, 9, 12, 13, 15, 18, 19, 16 1, 2, 5, 6, 8, 9, 12, 13, 15, 16, 18, 19

Quicksort Implementation /* Sort subarray a[i],… a[j] */ void quickSort(int a[ ], int i, int j) { int k; if (i >= j) return; k = partition(a, i, j); quickSort(a, i, k-1); quickSort(a, k+1, j); }

Partition(a, i, j) Restrict attention to the subarray a[i], ..., a[j] a[i] is the value of the pivot. Rearrange a[i], ..., a[j] so that elements less then the pivot are to the left of the pivot, and elements greater than the pivot are to the right of the pivot. Return the new position of the pivot.

Partition Examples partition(a, 0, 11) 12 15 18 8 2 19 5 13 16 9 6 1 12 15 18 8 2 19 5 13 16 9 6 1 8 2 5 9 6 1 12 15 18 19 13 16 partition(a, 4, 8) 2 5 8 9 16 11 19 15 13 27 21 23 2 5 8 9 11 15 13 16 19 27 21 23 returns 6 returns 7

A Partition Implementation /** partition a[i],... a[j] around pivot a[i] * @return new index of pivot */ int partition ( int a[ ], int i, int j ) { int pivot = a[i], left = i, right = j; while ( left < right ) { /* exchange next pair out of place */ while( left <= j && a[left] <= pivot ) left = left + 1; while ( a[right] > pivot && right >= I ) right = right -1; if ( left < right ) swap ( a, left, right ); } /* place pivot and return its index */ swap ( a, i, right ); return( right );

Call Graph quick_sort(a, 0, 11) quick_sort(a, 0, 5) quick_sort(a, 7, 11) quick_sort(a, 0, 3) quick_sort(a, 5, 5) quick_sort(a, 7, 7) quick_sort(a, 9, 11) quick_sort(a, 0, 0) quick_sort(a, 2, 3) quick_sort(a, 9, 9) quick_sort(a, 11, 11) quick_sort(a, 2, 1) quick_sort(a, 3, 3)