Programming with Recursion. Example of Recursion (Ask Until the User Gets It Right) import java.util.* ; public class CountDown { private int count; public.

Slides:



Advertisements
Similar presentations
Back to Sorting – More efficient sorting algorithms.
Advertisements

CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
Recursion Chapter 11. Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar with the binary.
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
Intro to CS – Honors I Merge Sort GEORGIOS PORTOKALIDIS
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
CS Data Structures I Chapter 10 Algorithm Efficiency & Sorting III.
Sorting Algorithms: Merge and Quick. Lecture Objectives Learn how to implement the simple advanced sorting algorithms (merge and quick) Learn how to implement.
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Recursion Chapter 11 Chapter 11.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Selection Sort -Reading p Reading p
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
1 Searching Algorithms Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
CSCD 326 Data Structures I Sorting
CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be.
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
Sorting Arrays. Selection Sort  One of the easiest ways to sort the elements of an array is by using the selection sort algorithm.  Assume that the.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
CS212: DATASTRUCTURES Lecture 3: Searching 1. Search Algorithms Sequential Search It does not require an ordered list. Binary Search It requires an ordered.
Analysis of Algorithms Dilemma: you have two (or more) methods to solve problem, how to choose the BEST? One approach: implement each algorithm in C, test.
ALGORITHM ANALYSIS AND DESIGN INTRODUCTION TO ALGORITHMS CS 413 Divide and Conquer Algortihms: Binary search, merge sort.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Building Java Programs Chapter 13 Searching reading: 13.3.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
COSC 2006 Data Structures I Recursion II
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sorting and Searching.
Analyzing Complexity of Lists OperationSorted Array Sorted Linked List Unsorted Array Unsorted Linked List Search( L, x ) O(logn) O( n ) O( n ) Insert(
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Computer Science Searching & Sorting.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
Chapter 15: Algorithms 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 15 Algorithms.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
Sort Algorithms.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
CS 46B: Introduction to Data Structures July 2 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Sorting  Sorting places data in ascending or descending order, based on one or more sort.
 MergeSort is a sorting algorithm which is more on the advanced end.  It is very fast, but unfortunately uses up a lot of memory due to the recursions.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
Merge Sort. In plain English: if the size of the array > 1, split the array into two halves, and recursively sort both halves; when the sorts return,
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Lecture 25: Searching and Sorting
Using recursion for Searching and Sorting
Fundamentals of Algorithms MCS - 2 Lecture # 11
Searching and Sorting Linear Search Binary Search ; Reading p
Building Java Programs
The Basics of Recursion
slides created by Marty Stepp
Recursion Chapter 11.
slides created by Marty Stepp
Basics of Recursion Programming with Recursion
slides created by Marty Stepp
Recursion Chapter 11.
CSE 373 Data Structures and Algorithms
Building Java Programs
slides adapted from Marty Stepp
Stacks, Queues, ListNodes
Sorting Algorithms.
Programming with Arrays 1
Presentation transcript:

Programming with Recursion

Example of Recursion (Ask Until the User Gets It Right) import java.util.* ; public class CountDown { private int count; public static void main(String[] args) { CountDown countDowner = new CountDown( ); countDowner.getCount( ); countDowner.showCountDown( ); } public void getCount( ) { System.out.println("Enter a positive number:"); Scanner keyboard = new Scanner(System.in); count = keyboard.nextInt( ); if (count = 0; left--) System.out.print(left + ", "); System.out.println("Blast Off!"); } }

Binary Search Using Recursion mid = approximate midpoint between first and last ; if (first > last) return -1; else if (target == a[mid]) return mid; else if (target < a[mid]) return the result of searching a[first] through a[mid-1]. else if (target > a[mid]) return the result of searching a[mid+1] through a[last].

Example of Recursion (Binary Search) /** Class for searching an already sorted array of ints. To search the sorted and completely filled array b, use the following: ArraySearcher bSearcher = new ArraySearcher(b); int index = bSearcher.find(target); index will be given an index of where target is located. index will be set to -1 if target is not in the array. */ public class ArraySearcher { private int[] a; /** Precondition: theArray is full and is sorted from lowest to highest. */ public ArraySearcher(int[] theArray) { a = theArray;//a is now another name for theArray. }

Example of Recursion (Binary Search) /** If target is in the array, returns the index of an occurrence of target. Returns -1 if target is not in the array. */ public int find(int target) { return search(target, 0, a.length - 1); } //Uses binary search to search for target in a[first] through //a[last] inclusive. Returns the index of target if target //is found. Returns -1 if target is not found. private int search(int target, int first, int last) { int result = -1;//to keep the compiler happy. int mid; if (first > last) result = -1; else { mid = (first + last)/2; if (target == a[mid]) result = mid; else if (target a[mid]) result = search(target, mid + 1, last); } return result; } }

Example of Recursion (Binary Search) import java.util.*; public class ArraySearcherDemo { public static void main(String[] args) { int [] a = new int[10]; System.out.println("Enter 10 integers in increasing order."); System.out.println("One per line."); Scanner keyboard = new Scanner(System.in); int i; for (i = 0; i < 10; i++) a[i] = keyboard.nextInt( ); System.out.println( ); for (i = 0; i < 10; i++) System.out.print("a[" + i + "]=" + a[i] + " "); System.out.println( ); System.out.println( ); ArraySearcher finder = new ArraySearcher(a); String ans; do { System.out.println("Enter a value to search for:"); int target = keyboard.nextInt( ); int result = finder.find(target); if (result < 0) System.out.println( target + " is not in the array."); else System.out.println( target + " is at index " + result); System.out.println("Again?"); ans = keyboard.next( ); }while (ans.equalsIgnoreCase("yes")); System.out.println( "May you find what you're searching for."); } }

Merge Sort – A Recursive Sorting Method  Merge sort is an example of a divide- and-conquer algorithm.  The array to be sorted is divided in half, and the two halves of the array are sorted by recursive calls.  That process produces two smaller sorted arrays.  The two sorted arrays are then merged to form a single sorted array.

Merge Sort – A Recursive Sorting Method Algorithm  If the array a has only one element do nothing (stopping case).  Otherwise, do the following (recursive case): Copy the first half of the elements in a to a smaller array named front. Copy the rest of the elements in the array a to another smaller array named tail. Sort the array front with a recursive call. Sort the array tail with a recursive call. Merge the elements in the arrays front and tail into the array a.

Merge Sort – A Recursive Sorting Method Code /** Class for sorting an array of ints from smallest to largest, using the merge sort algorithm. */ public class MergeSort { /** Precondition: Every indexed variable of a has a value. Action: Sorts a so that a[0] = 2) { int halfLength = a.length/2; int[] front = new int[halfLength]; int[] tail = new int[a.length - halfLength]; divide(a, front, tail); sort(front); sort(tail); merge(a, front, tail); } //else do nothing. a.length == 1, so a is sorted. }

Merge Sort – A Recursive Sorting Method Code (cont’d) /** Precondition: a.length = front.length + tail.length. Postcondition: All the elements of a are divided between the arrays front and tail. */ private static void divide(int[] a, int[] front, int[] tail) { int i; for (i = 0; i < front.length; i++) front[i] = a[i]; for (i = 0; i < tail.length; i++) tail[i] = a[front.length + i]; }

Merge Sort – A Recursive Sorting Method Code (cont’d) /** Precondition: Arrays front and tail are sorted from smallest to largest, and a.length = front.length + tail.length. Postcondition: a contains all the values from front and tail, and a is sorted from smallest to largest. */ private static void merge(int[] a, int[] front, int[] tail) { int frontIndex = 0, tailIndex = 0, aIndex = 0; while ((frontIndex < front.length) && (tailIndex < tail.length)) { if (front[frontIndex] < tail[tailIndex]) { a[aIndex] = front[frontIndex]; aIndex++; frontIndex++; } else { a[aIndex] = tail[tailIndex]; aIndex++; tailIndex++; } } //At least one of front and tail has been //completely copied to a. while (frontIndex < front.length)//Copy rest of front, //if any. { a[aIndex] = front[frontIndex]; aIndex++; frontIndex++; } while (tailIndex < tail.length)//Copy rest of tail, if any. { a[aIndex] = tail[tailIndex]; aIndex++; tailIndex++; } } }

Merge Sort – A Recursive Sorting Method Code (cont’d) public class MergeSortDemo { public static void main(String[] args) { int[] b = {7, 5, 11, 2, 16, 4, 18, 14, 12, 30}; System.out.println("Array values before sorting:"); int i; for (i = 0; i < b.length; i++) System.out.print(b[i] + " "); System.out.println( ); MergeSort.sort(b); System.out.println("Array values after sorting:"); for (i = 0; i < b.length; i++) System.out.print(b[i] + " "); System.out.println( ); } }