Fall 2006CSC311: Data Structures1 Chapter 3 Arrays, Linked Lists, and Recursion Objectives –Using Arrays –Singly Linked Lists –Doubly Linked Lists –Circularly.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Queues and Linked Lists
LEVEL II, TERM II CSE – 243 MD. MONJUR-UL-HASAN LECTURER DEPT OF CSE, CUET Recursive & Dynamic Programming.
CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
CSE Lecture 3 – Algorithms I
M180: Data Structures & Algorithms in Java
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
© 2004 Goodrich, Tamassia Using Recursion1 Programming with Recursion.
Data Structures Chuan-Ming Liu
Algorithm Design Techniques: Induction Chapter 5 (Except Sections 5.6 and 5.7)
© 2004 Goodrich, Tamassia Using Recursion1. © 2004 Goodrich, Tamassia Using Recursion2 Recall the Recursion Pattern (§ 2.5) Recursion: when a method calls.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Linked Lists. Example We would like to keep a list of inventory records – but only as many as we need An array is a fixed size Instead – use a linked.
Algorithm Design Techniques: Induction Chapter 5 (Except Section 5.6)
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Revision Using Recursion1 Recursion. Revision Using Recursion2 Recall the Recursion Pattern Recursion: when a method calls itself Classic example--the.
 Last lesson  Arrays for implementing collection classes  Performance analysis (review)  Today  Performance analysis  Logarithm.
© 2004 Goodrich, Tamassia Using Recursion1. © 2004 Goodrich, Tamassia Using Recursion2 Recall the Recursion Pattern (§ 2.5) Recursion: when a method calls.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Chapter 3: Arrays, Linked Lists, and Recursion
Programming with Recursion
Recursion.
Recursion Chapter 5 Outline Induction Linear recursion –Example 1: Factorials –Example 2: Powers –Example 3: Reversing an array Binary recursion –Example.
Fibonacci numbers Fibonacci numbers:Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,... where each number is the sum of the preceding two. Recursive.
Data Structures Using C++ 2E Chapter 6 Recursion.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Data Structures Using C++ 2E Chapter 6 Recursion.
Introduction to Recursion by Dr. Bun Yue Professor of Computer Science 2013
Using Recursion1 Recursion © 2010 Goodrich, Tamassia.
1 Object-Oriented Programming Using C++ CLASS 2. 2 Linear Recursion Summing the Elements of an Array Recursively Algorithm LinearSum(A, n): Input: An.
Lecture 8. How to Form Recursive relations 1. Recap Asymptotic analysis helps to highlight the order of growth of functions to compare algorithms Common.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
CS212D : DATA STRUCTURES 1 Week 5-6 Linked List. Outline 2  Singly Linked Lists  Doubly Linked Lists  Recursions.
Introduction to Recursion CSCI 3333 Data Structures.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Recursion Trees1 Recursion is a concept of defining a method that makes a call to itself.
CSC 212 More Recursion, Stacks, & Queues. Linear Recursion Test for the bases cases  At least one base case needs to be defined If not at a base case,
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Lecture 9COMPSCI.220.FS.T Lower Bound for Sorting Complexity Each algorithm that sorts by comparing only pairs of elements must use at least 
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
23 February Recursion and Logarithms CSE 2011 Winter 2011.
Recursion1 © 2013 Goodrich, Tamassia, Goldwasser.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Given a node v of a doubly linked list, we can easily insert a new node z immediately after v. Specifically, let w the be node following v. We execute.
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! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
LINKED LISTS.
COMP9024: Data Structures and Algorithms
Lecture 6 of Computer Science II
Recursion 5/4/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Recursion 5/22/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Searching – Linear and Binary Searches
Recursion and Logarithms
EEL 4854 IT Data Structures Linked Lists
Recursion © 2013 Goodrich, Tamassia, Goldwasser Recursion Sequences
Linked Lists.
CS212D: Data Structures Week 5-6 Linked List.
Recall Brute Force as a Problem Solving Technique
Programming with Recursion
Programming with Recursion
CS210- Lecture 3 Jun 6, 2005 Announcements
Sequences 6/1/2019 7:49 PM Using Recursion Using Recursion.
Recursion © 2013 Goodrich, Tamassia, Goldwasser Recursion Sequences
Presentation transcript:

Fall 2006CSC311: Data Structures1 Chapter 3 Arrays, Linked Lists, and Recursion Objectives –Using Arrays –Singly Linked Lists –Doubly Linked Lists –Circularly Linked Lists –Linked-List Sorting –Recursion

Fall 2006CSC311: Data Structures2 Arrays DeclarationProperties –Index: 0 through length-1 –Length: the number of elements –Fixed length –Elements could be objects Operations –Insertion: add(Object e) –Deletion: remove(Object e) remove(int i) –Search: find(Object e)

Fall 2006CSC311: Data Structures3 Sorting an Array Insertion-sort algorithm Selection-sort algorithm Merge-sort algorithm Bubble-sort algorithm Quick-sort algorithm

Fall 2006CSC311: Data Structures4 java.util Methods for Arrays Simple methods –equals(A, B) –fill(A, x) –sort(A) –toString(A)

Fall 2006CSC311: Data Structures5 Pseudo-Random Numbers Random rand = new Random(); Rand.setSeed(System.currentTimeMills());…… rand.nextInt(100); // between 0 and 99 Pseudo-random number generator seed

Fall 2006CSC311: Data Structures6 Two-Dmensional Arrays Array of arrays –Index –Length –Reference –Assignment of arrays Matrix High-dimension arrays

Fall 2006CSC311: Data Structures7 Singly Linked Lists Linked list: a collection of nodes in a linear order Nodes –Link – pointing to the next node –Data Head – refer to the first node Operations: –Insertion addFirst(Object)-- O(1) addLast(Object)-- O(1) –Removal removeFirst()-- O(1) removeLast()-- O(1) –Search find(Object)-- O(n) Implementation –Boundary scenarios: insert into and remove from an empty list

Fall 2006CSC311: Data Structures8 Doubly Linked Lists Doubly linked list – a linked list with each node having two links pointing to its previous and next nodes respectively Node: DNode –Fields: Data – element Link to previous node – prev Link to next node – next –Methods: getElement()getNext()getPrev()setElement(Object)setNext(DNode)setPrev(DNode)

Fall 2006CSC311: Data Structures9 Doubly Linked Lists Header and Trailer Sentinels –Separate header and trailer One header, one trailer –Integrated header and trailer One node with prev pointing to the last node and next pointing to the first node Operations – at ends –Insertion –Removal Operations – in the middle –Insertion –removal

Fall 2006CSC311: Data Structures10 Circularly Linked Lists A linked list without head or tail Traversal means circle through all nodes Cursor: current node Operations: –add(Object) – immediately after the cursor –remove() – immediately after the cursor –advance() – go to the next node

Fall 2006CSC311: Data Structures11 Sorting a Linked List Insertion-sort –Using single linked list Start from the first to the current Find the appropriate position and insert –Using two linked list Remove the first from the source list Insert into the target list Selection-sort –Using single linked list Select the maximum from the original first Insert at the first –Using two linked list Select the minimum from the source list Insert at the last to the target list

Fall 2006CSC311: Data Structures12 Recursion Pattern Recursion: when a method calls itself Classic example--the factorial function: –n! = 1 · 2 · 3 · ··· · (n-1) · n Recursive definition: As a Java method: // recursive factorial function public static int recursiveFactorial(int n) { if ( n == 0 ) return 1 ; // basis case if ( n == 0 ) return 1 ; // basis case else return n * recursiveFactorial ( n- 1 ); // recursive case else return n * recursiveFactorial ( n- 1 ); // recursive case}

Fall 2006CSC311: Data Structures13 Linear Recursion Test for base cases. –Begin by testing for a set of base cases (there should be at least one). –Every possible chain of recursive calls must eventually reach a base case, and the handling of each base case should not use recursion. Recur once. –Perform a single recursive call. (This recursive step may involve a test that decides which of several possible recursive calls to make, but it should ultimately choose to make just one of these calls each time we perform this step.) –Define each possible recursive call so that it makes progress towards a base case.

Fall 2006CSC311: Data Structures14 A Simple Example of Linear Recursion Algorithm LinearSum(A, n): Input: An integer array A and an integer n  1, such that A has at least n elements An integer array A and an integer n  1, such that A has at least n elementsOutput: The sum of the first n integers in A The sum of the first n integers in A if n = 1 then return A[0] return A[0]else return LinearSum(A, n - 1) + A[n - 1] return LinearSum(A, n - 1) + A[n - 1] Example recursion trace:

Fall 2006CSC311: Data Structures15 Reversing an Array Algorithm ReverseArray(A, i, j): Input: An array A and nonnegative integer indices i and j Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j Output: The reversal of the elements in A starting at index i and ending at j if i < j then if i < j then Swap A[i] and A[ j] Swap A[i] and A[ j] ReverseArray(A, i + 1, j - 1) ReverseArray(A, i + 1, j - 1) return return

Fall 2006CSC311: Data Structures16 Defining Arguments for Recursion In creating recursive methods, it is important to define the methods in ways that facilitate recursion. This sometimes requires we define additional parameters that are passed to the method. For example, we defined the array reversal method as ReverseArray(A, i, j), not ReverseArray(A).

Fall 2006CSC311: Data Structures17 Computing Powers The power function, p(x,n)=x n, can be defined recursively: This leads to an power function that runs in O(n) time (for we make n recursive calls). We can do better than this, however.

Fall 2006CSC311: Data Structures18 Recursive Squaring We can derive a more efficient linearly recursive algorithm by using repeated squaring: For example, 2 4 = 2 ( 4 / 2 ) 2 = ( 2 4 / 2 ) 2 = ( 2 2 ) 2 = 4 2 = = 2 1 +( 4 / 2 ) 2 = 2 ( 2 4 / 2 ) 2 = 2 ( 2 2 ) 2 = 2 ( 4 2 ) = = 2 ( 6 / 2)2 = ( 2 6 / 2 ) 2 = ( 2 3 ) 2 = 8 2 = = 2 1 +( 6 / 2 ) 2 = 2 ( 2 6 / 2 ) 2 = 2 ( 2 3 ) 2 = 2 ( 8 2 ) = 128.

Fall 2006CSC311: Data Structures19 A Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Input: A number x and integer n = 0 Output: The value x n Output: The value x n if n = 0then if n = 0then return 1 if n is odd then if n is odd then y = Power(x, (n - 1)/ 2) return x · y ·y else else y = Power(x, n/ 2) return y · y

Fall 2006CSC311: Data Structures20 Analyzing the Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Input: A number x and integer n = 0 Output: The value x n Output: The value x n if n = 0then if n = 0then return 1 return 1 if n is odd then if n is odd then y = Power(x, (n - 1)/ 2) y = Power(x, (n - 1)/ 2) return x · y · y return x · y · y else else y = Power(x, n/ 2) y = Power(x, n/ 2) return y · y return y · y It is important that we used a variable twice here rather than calling the method twice. Each time we make a recursive call we halve the value of n; hence, we make log n recursive calls. That is, this method runs in O(log n) time.

Fall 2006CSC311: Data Structures21 Tail Recursion Tail recursion occurs when a linearly recursive method makes its recursive call as its last step. The array reversal method is an example. Such methods can be easily converted to non- recursive methods (which saves on some resources). Example: Algorithm IterativeReverseArray(A, i, j ): Input: An array A and nonnegative integer indices i and j Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j Output: The reversal of the elements in A starting at index i and ending at j while i < j do while i < j do Swap A[i ] and A[ j ] i = i + 1 j = j - 1 return return

Fall 2006CSC311: Data Structures22 Binary Recursive Method Binary recursion occurs whenever there are two recursive calls for each non-base case. Example Problem: add all the numbers in an integer array A: Algorithm BinarySum(A, i, n): Input: An array A and integers i and n Input: An array A and integers i and n Output: The sum of the n integers in A starting at index i Output: The sum of the n integers in A starting at index i if n = 1 then if n = 1 then return A[i ] return A[i ] return BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2) return BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2) Example trace:

Fall 2006CSC311: Data Structures23 Computing Fibanacci Numbers Fibonacci numbers are defined recursively: F 0 = 0 F 1 = 1 F i = F i F i - 2 for i > 1. As a recursive algorithm (first attempt): Algorithm BinaryFib( k ) : Input: Nonnegative integer k Input: Nonnegative integer k Output: The kth Fibonacci number F k Output: The kth Fibonacci number F k if k < = 1 then if k < = 1 then return k return k else else return BinaryFib( k - 1 ) + BinaryFib( k - 2 ) return BinaryFib( k - 1 ) + BinaryFib( k - 2 )

Fall 2006CSC311: Data Structures24 Analyzing the Binary Recursion Fibonacci Algorithm Let n k denote number of recursive calls made by BinaryFib(k). Then –n 0 = 1 –n 1 = 1 –n 2 = n 1 + n = = 3 –n 3 = n 2 + n = = 5 –n 4 = n 3 + n = = 9 –n 5 = n 4 + n = = 15 –n 6 = n 5 + n = = 25 –n 7 = n 6 + n = = 41 –n 8 = n 7 + n = = 67. Note that the value at least doubles for every other value of n k. That is, n k > 2 k/2. It is exponential!

Fall 2006CSC311: Data Structures25 A Better Fibonacci Algorithm Use linear recursion instead: Algorithm LinearFibonacci(k): Input: A nonnegative integer k Input: A nonnegative integer k Output: Pair of Fibonacci numbers (F k, F k-1 ) Output: Pair of Fibonacci numbers (F k, F k-1 ) if k <= 1 then if k <= 1 then return (k, 0) else else (i, j) = LinearFibonacci(k - 1) return (i +j, i) Runs in O(k) time.

Fall 2006CSC311: Data Structures26 Multiple Recursion Motivating example: summation puzzles pot + pan = bib dog + cat = pig boy + girl = baby Multiple recursion: makes potentially many recursive calls (not just one or two).

Fall 2006CSC311: Data Structures27 Algorithm for Multiple Recursion Algorithm PuzzleSolve(k,S,U): Input: An integer k, sequence S, and set U (the universe of elements to test) Input: An integer k, sequence S, and set U (the universe of elements to test) Output: An enumeration of all k-length extensions to S using elements in U without repetitions Output: An enumeration of all k-length extensions to S using elements in U without repetitions for all e in U do for all e in U do Remove e from U {e is now being used} Add e to the end of S if k = 1 then Test whether S is a configuration that solves the puzzle if S solves the puzzle then return “Solution found: ” S else PuzzleSolve(k - 1, S,U) Add e back to U {e is now unused} Remove e from the end of S

Fall 2006CSC311: Data Structures28 Visualizing PuzzleSolve