COM328M2: Algorithms and Data Structures - PowerPoint PPT Presentation

1 / 51
About This Presentation
Title:

COM328M2: Algorithms and Data Structures

Description:

return numb * fac(numb-1); Recursion means that a function calls itself. Factorial function ... (int numb, int power) recursively? int exp(int numb, int power) ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 52
Provided by: franz158
Category:

less

Transcript and Presenter's Notes

Title: COM328M2: Algorithms and Data Structures


1
COM328M2 Algorithms and Data Structures
  • Dr Zumao Weng
  • http//www.infm.ulst.ac.uk/zumao/teaching/COM328M
    2
  • School of Computing and Intelligent Systems
  • University of Ulster at Magee
  • 9-2-2009

2
Chapter 3 Recursion and Linked List
3
Recursion
  • In some problems, it may be natural to define the
    problem in terms of the problem itself.
  • Recursion is useful for problems that can be
    represented by a simpler version of the same
    problem.
  • Example the factorial function
  • 6! 6 5 4 3 2 1
  • We could write
  • 6! 6 5!

4
Example 1 Factorial function
  • In general, we can express the factorial function
    as follows
  • n! n (n-1)!
  • Is this correct? Well almost.
  • The factorial function is only defined for
    positive integers. So we should be a bit more
    precise
  • n! 1 (if n is equal to 1)
  • n! n (n-1)! (if n is larger than 1)

5
Factorial function
  • The C equivalent of this definition
  • int fac(int numb)
  • if(numblt1)
  • return 1
  • else
  • return numb fac(numb-1)
  • Recursion means that a function calls itself

6
Factorial function
  • Assume the number typed is 3, that is, numb3.
    fac(3)

3 lt 1 ? No. fac(3) 3 fac(2)
fac(2) 2 lt 1 ? No. fac(2) 2 fac(1)
fac(1) 1 lt 1 ? Yes. return 1
int fac(int numb) if(numblt1) return
1 else return numb fac(numb-1)
fac(2) 2 1 2 return fac(2)
fac(3) 3 2 6 return fac(3)
fac(3) has the value 6
7
Factorial function
  • For certain problems (such as the factorial
    function), a recursive solution often leads to
    short and elegant code. Compare the recursive
    solution with the iterative solution

  • Iterative solution

  • int fac(int numb)


  • int product1
  • while(numbgt1)
  • product numb
  • numb--

  • return product
  • Recursive solution
  • int fac(int numb)
  • if(numblt1)
  • return 1
  • else
  • return numbfac(numb-1)

8
Recursion
  • To trace recursion, recall that function calls
    operate as a stack the new function is put on
    top of the caller
  • We have to pay a price for recursion
  • calling a function consumes more time and memory
    than adjusting a loop counter.
  • high performance applications (graphic action
    games, simulations of nuclear explosions) hardly
    ever use recursion.
  • In less demanding applications recursion is an
    attractive alternative for iteration (for the
    right problems!)

9
Recursion
  • If we use iteration, we must be careful not to
    create an infinite loop by accident
  • for ( int incr 1 incr ! 10 incr 2)
  • . . .
  • int result 1
  • while (result gt0)
  • . . .
  • result

Oops!
Oops!
10
Recursion
  • Similarly, if we use recursion we must be
    careful not to create an infinite chain of
    function calls
  • int fac( int numb)
  • return numb fac(numb-1)
  • Or
  • int fac( int numb)
  • if (numblt1)
  • return 1
  • else
  • return numb fac( numb1)

Oops! No termination condition
Oops!
11
Recursion
  • We must always make sure that the recursion
    bottoms out
  • A recursive function must contain at least one
    non-recursive branch.
  • The recursive calls must eventually lead to a
    non-recursive branch.

12
Recursion
  • Recursion is one way to decompose a task into
    smaller subtasks. At least one of the subtasks is
    a smaller example of the same task.
  • The smallest example of the same task has a
    non-recursive solution.
  • Example The factorial function
  • n! n (n-1)! and 1! 1

13
Example 2 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 definition
  • F(0) 0
  • F(1) 1
  • F(number) F(number-1) F(number-2)

14
(No Transcript)
15
Example 3 Fibonacci numbers
  • //Calculate Fibonacci numbers using recursive
    function.
  • //A very inefficient way, but illustrates
    recursion well
  • int fib(int number)
  • if (number 0) return 0
  • if (number 1) return 1
  • return (fib(number-1) fib(number-2))
  • int main() // driver function
  • int inp_number
  • cout ltlt "Please enter an integer "
  • cin gtgt inp_number
  • cout ltlt "The Fibonacci number for "ltlt inp_number
  • ltlt " is "ltlt fib(inp_number)ltltendl
  • return 0

16
(No Transcript)
17
Trace a Fibonacci Number
int fib(int num) if (num 0) return 0 if
(num 1) return 1 return
(fib(num-1)fib(num-2))
  • Assume the input number is 4, that is, num4
  • fib(4)
  • 4 0 ? No 4 1? No.
  • fib(4) fib(3) fib(2)
  • fib(3)
  • 3 0 ? No 3 1? No.
  • fib(3) fib(2) fib(1)
  • fib(2)
  • 2 0? No 21? No.
  • fib(2) fib(1)fib(0)
  • fib(1)
  • 1 0 ? No 1 1? Yes.
  • fib(1) 1
  • return fib(1)

18
Trace a Fibonacci Number
fib(0) 0 0 ? Yes.
fib(0) 0 return fib(0) fib(2)
1 0 1 return fib(2) fib(3) 1
fib(1) fib(1) 1 0 ? No 1 1?
Yes fib(1) 1 return fib(1)
fib(3) 1 1 2 return fib(3)
19
Trace a Fibonacci Number
  • fib(2)
  • 2 0 ? No 2 1? No.
  • fib(2) fib(1) fib(0)
  • fib(1)
  • 1 0 ? No 1 1? Yes.
  • fib(1) 1
  • return fib(1)
  • fib(0)
  • 0 0 ? Yes.
  • fib(0) 0
  • return fib(0)
  • fib(2) 1 0 1
  • return fib(2)
  • fib(4) fib(3) fib(2)
  • 2 1 3
  • return fib(4)

20
Fibonacci number w/o recursion
  • //Calculate Fibonacci numbers iteratively
  • //much more efficient than recursive solution
  • int fib(int n)
  • int fn1
  • f0 0 f1 1
  • for (int i2 ilt n i)
  • fi fi-1 fi-2
  • return fn

21
Example 3 Binary Search
  • Search for an element in an array
  • Sequential search
  • Binary search
  • Binary search
  • Compare the search element with the middle
    element of the array
  • If not equal, then apply binary search to half of
    the array
  • (if not empty) where the search element would
    be.

22
Binary Search w/o recursion
  • // Searches an ordered array of integers
  • int bsearch(const int data, // input array
  • int size, // input array size
  • int value // input value to find
  • ) // output if
    found,return
  • // index otherwise,
    return -1
  • int first, last, upper
  • first 0
  • last size - 1
  • while (true)
  • middle (first last) / 2
  • if (datamiddle value)
  • return middle
  • else if (first gt last)
  • return -1
  • else if (value lt datamiddle)
  • last middle - 1
  • else

23
Recursion General Form
  • How to write recursively?
  • int recur_fn(parameters)
  • if(stopping condition)
  • return stopping value
  • // other stopping conditions if needed
  • return function of recur_fn(revised
  • parameters)

24
Example 4 exponential function
  • How to write exp(int numb, int power)
    recursively?
  • int exp(int numb, int power)
  • if(power 0)
  • return 1
  • return numb exp(numb, power -1)

25
Example 5 number of zero
  • Write a recursive function that counts the number
    of zero digits in an integer
  • zeros(10200) returns 3.
  • int zeros( int numb)
  • if (numb0) // 1 digit
    (zero/non-zero)
  • return 1 // bottom out.
  • else if (numb lt 10 numb gt -10)
  • return 0
  • else // gt 1 digits recursion
  • return zeros(numb/10) zeros(numb10)

zeros(10200) zeros(1020)
zeros(0) zeros(102)
zeros(0)
zeros(0) zeros(10) zeros(2)
zeros(0) zeros(0) zeros(1) zeros(0)
zeros(2) zeros(0) zeros(0)
26
Example 6 Towers of Hanoi
  • Only one disc could be moved at a time
  • A larger disc must never be stacked above a
    smaller one
  • One and only one extra needle could be used for
    intermediate storage of discs

see applet
27
Towers of Hanoi
  • void hanoi(int from, int to, int num)
  • int temp 6 - from - to //find the
    temporary
  • //storage column
  • if (num 1)
  • cout ltlt "move disc 1 from " ltlt from
  • ltlt " to " ltlt to ltlt endl
  • else
  • hanoi(from, temp, num - 1)
  • cout ltlt "move disc " ltlt num ltlt " from "
    ltlt from
  • ltlt " to " ltlt to ltlt endl
  • hanoi(temp, to, num - 1)

28
Towers of Hanoi
  • int main()
  • int num_disc //number of discs
  • cout ltlt "Please enter a positive number (0 to
    quit)"
  • cin gtgt num_disc
  • while (num_disc gt 0)
  • hanoi(1, 3, num_disc)
  • cout ltlt "Please enter a positive number
    "
  • cin gtgt num_disc
  • return 0

29
  • Linked Lists

30
List Overview
  • Linked lists
  • Abstract data type (ADT)
  • Basic operations of linked lists
  • Insert, find, delete, print, etc.
  • Variations of linked lists
  • Circular linked lists
  • Doubly linked lists

31
Linked Lists
?
Head
  • A linked list is a series of connected nodes
  • Each node contains at least
  • A piece of data (any type)
  • Pointer to the next node in the list
  • Head pointer to the first node
  • The last node points to NULL

node
data
pointer
32
A Simple Linked List Class
  • We use two classes Node and List
  • Declare Node class for the nodes
  • data double-type data in this example
  • next a pointer to the next node in the list

class Node public double data //
data Node next // pointer to next
33
A Simple Linked List Class
  • Declare List, which contains
  • head a pointer to the first node in the list.
  • Since the list is empty initially, head is
    set to NULL
  • Operations on List
  • class List
  • public
  • List(void) head NULL // constructor
  • List(void) // destructor
  • bool IsEmpty() return head NULL
  • Node InsertNode(int index, double x)
  • int FindNode(double x)
  • int DeleteNode(double x)
  • void DisplayList(void)
  • private
  • Node head

34
A Simple Linked List Class
  • Operations of List
  • IsEmpty determine whether or not the list is
    empty
  • InsertNode insert a new node at a particular
    position
  • FindNode find a node with a given value
  • DeleteNode delete a node with a given value
  • DisplayList print all the nodes in the list

35
Inserting a new node
  • Node InsertNode(int index, double x)
  • Insert a node with data equal to x after the
    indexth elements. (i.e., when index 0, insert
    the node as the first element
  • when index 1, insert the node after the
    first element, and so on)
  • If the insertion is successful, return the
    inserted node.
  • Otherwise, return NULL.
  • (If index is lt 0 or gt length of the list,
    the insertion will fail.)
  • Steps
  • Locate indexth element
  • Allocate memory for the new node
  • Point the new node to its successor
  • Point the new nodes predecessor to the new node

indexth element
newNode
36
Inserting a new node
  • Possible cases of InsertNode
  • Insert into an empty list
  • Insert in front
  • Insert at back
  • Insert in middle
  • But, in fact, only need to handle two cases
  • Insert as the first node (Case 1 and Case 2)
  • Insert in the middle or at the end of the list
    (Case 3 and Case 4)

37
Inserting a new node
Try to locate indexth node. If it doesnt exist,
return NULL.
Node ListInsertNode(int index, double x) if
(index lt 0) return NULL int
currIndex 1 Node currNode head while
(currNode index gt currIndex)
currNode currNode-gtnext currIndex
if (index gt 0 currNode NULL) return
NULL Node newNode new Node newNode-gtdata
x if (index 0) newNode-gtnext head
head newNode else newNode-gtnext cur
rNode-gtnext currNode-gtnext newNode retur
n newNode
38
Inserting a new node
Node ListInsertNode(int index, double x) if
(index lt 0) return NULL int
currIndex 1 Node currNode head while
(currNode index gt currIndex)
currNode currNode-gtnext currIndex
if (index gt 0 currNode NULL) return
NULL Node newNode new Node newNode-gtdata
x if (index 0) newNode-gtnext
head head newNode else
newNode-gtnext currNode-gtnext currNode-gtne
xt newNode return newNode
Create a new node
39
Inserting a new node
Node ListInsertNode(int index, double x) if
(index lt 0) return NULL int
currIndex 1 Node currNode head while
(currNode index gt currIndex)
currNode currNode-gtnext currIndex
if (index gt 0 currNode NULL) return
NULL Node newNode new Node newNode-gtdata
x if (index 0) newNode-gtnext head
head newNode else newNode-gtnext cur
rNode-gtnext currNode-gtnext newNode retur
n newNode
Insert as first element
head
newNode
40
Inserting a new node
Node ListInsertNode(int index, double x) if
(index lt 0) return NULL int
currIndex 1 Node currNode head while
(currNode index gt currIndex)
currNode currNode-gtnext currIndex
if (index gt 0 currNode NULL) return
NULL Node newNode new Node newNode-gtdata
x if (index 0) newNode-gtnext head
head newNode else newNode-gtnext cur
rNode-gtnext currNode-gtnext newNode retur
n newNode
Insert after currNode
currNode
newNode
41
Finding a node
  • int FindNode(double x)
  • Search for a node with the value equal to x in
    the list.
  • If such a node is found, return its position.
    Otherwise, return 0.

int ListFindNode(double x) Node
currNode head int currIndex 1 while
(currNode currNode-gtdata ! x)
currNode currNode-gtnext currIndex
if (currNode) return currIndex return 0
42
Deleting a node
  • int DeleteNode(double x)
  • Delete a node with the value equal to x from the
    list.
  • If such a node is found, return its position.
    Otherwise, return 0.
  • Steps
  • Find the desirable node (similar to FindNode)
  • Release the memory occupied by the found node
  • Set the pointer of the predecessor of the found
    node to the successor of the found node
  • Like InsertNode, there are two special cases
  • Delete first node
  • Delete the node in middle or at the end of the
    list

43
Deleting a node
int ListDeleteNode(double x) Node
prevNode NULL Node currNode head int
currIndex 1 while (currNode currNode-gtdata
! x) prevNode currNode currNode currNo
de-gtnext currIndex if
(currNode) if (prevNode) prevNode-gtnext
currNode-gtnext delete currNode else
head currNode-gtnext delete
currNode return currIndex return 0
Try to find the node with its value equal to x
44
Deleting a node
int ListDeleteNode(double x) Node
prevNode NULL Node currNode head int
currIndex 1 while (currNode currNode-gtdata
! x) prevNode currNode currNode currNo
de-gtnext currIndex if (currNode) if
(prevNode) prevNode-gtnext currNode-gtnext
delete currNode else head currNod
e-gtnext delete currNode return
currIndex return 0
currNode
prevNode
45
Deleting a node
int ListDeleteNode(double x) Node
prevNode NULL Node currNode head int
currIndex 1 while (currNode currNode-gtdata
! x) prevNode currNode currNode currNo
de-gtnext currIndex if (currNode) if
(prevNode) prevNode-gtnext currNode-gtnext
delete currNode else head currNod
e-gtnext delete currNode return
currIndex return 0
currNode
head
46
Printing all the elements
  • void DisplayList(void)
  • Print the data of all the elements
  • Print the number of the nodes in the list

void ListDisplayList() int num 0
Node currNode head while (currNode !
NULL) cout ltlt currNode-gtdata ltlt
endl currNode currNode-gtnext num
cout ltlt "Number of nodes in the list " ltlt num ltlt
endl
47
Destroying the list
  • List(void)
  • Use the destructor to release all the memory used
    by the list.
  • Step through the list and delete each node one by
    one.

ListList(void) Node currNode head,
nextNode NULL while (currNode ! NULL)
nextNode currNode-gtnext // destroy the
current node delete currNode currNode nextNo
de
48
Using List
6 7 5 Number of nodes in the list 3 5.0
found 4.5 not found 6 5 Number of nodes in the
list 2
result
int main(void) List list list.InsertNode(0,
7.0) // successful list.InsertNode(1, 5.0) //
successful list.InsertNode(-1, 5.0) //
unsuccessful list.InsertNode(0, 6.0) //
successful list.InsertNode(8, 4.0) //
unsuccessful // print all the elements list.Disp
layList() if(list.FindNode(5.0) gt 0) cout ltlt
"5.0 found" ltlt endl else cout ltlt "5.0 not
found" ltlt endl if(list.FindNode(4.5) gt 0) cout
ltlt "4.5 found" ltlt endl else cout ltlt "4.5 not
found" ltlt endl list.DeleteNode(7.0) list.Displ
ayList() return 0
49
Variations of Linked Lists
  • Circular linked lists
  • The last node points to the first node of the
    list
  • How do we know when we have finished traversing
    the list? (Tip check if the pointer of the
    current node is equal to the head.)

Head
50
Variations of Linked Lists
  • Doubly linked lists
  • Each node points to not only successor but the
    predecessor
  • There are two NULL at the first and last nodes
    in the list
  • Advantage given a node, it is easy to visit its
    predecessor. Convenient to traverse lists
    backwards

?
?
Head
51
Array versus Linked Lists
  • Linked lists are more complex to code and manage
    than arrays, but they have some distinct
    advantages.
  • Dynamic a linked list can easily grow and shrink
    in size.
  • We dont need to know how many nodes will be in
    the list. They are created in memory as needed.
  • In contrast, the size of a C array is fixed at
    compilation time.
  • Easy and fast insertions and deletions
  • To insert or delete an element in an array, we
    need to copy to temporary variables to make room
    for new elements or close the gap caused by
    deleted elements.
  • With a linked list, no need to move other nodes.
    Only need to reset some pointers.
Write a Comment
User Comments (0)
About PowerShow.com