# 4. Recursion - MATH 224 Discrete Mathematics Recursive C+...

This preview shows pages 1–4. Sign up to view the full content.

8/27/09 11 MATH 224 – Discrete Mathematics Iterative version Recursive version Normally i is initialized to 0 and j to n–1 for an array of size n . Recursive C++ Functions int binary_search(in x, int a[ ], int i, int j) while (i < j) { m = (i+j)/2; if (x > a[m]) i = m+1; else j = m } //end while return i; } //end binary_search int binary_search(int x, int a[ ], int i, int j) if (i < j) { m = (i+j)/2; if (x > a[m]) i = bin_search(x, a, m+1, j) ; else i = bin_search(x, a, i, m) ; } //fi return i; } //end binary_search

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
8/27/09 22 MATH 224 – Discrete Mathematics Recursive C++ Functions With the recursive version of binary search below, how many times will binary_search call it self for an array of size N? What will happen if x is not in array a ? int binary_search(int x, int a[ ], int i, int j) if (i < j) { m = (i+j)/2; if (x > a[m]) i = bin_search(x, a, m+1, j) ; else i = bin_search(x, a, i, m) ; } //fi return i; } //end binary_search
8/27/09 33 MATH 224 – Discrete Mathematics Recursive C++ Functions and the Program Stack x = 14, i =3, j =3 x = 14, i =3, j =4, m = 3 x = 14, i =3, j =5, m = 4 x = 14, i =0, j =5, m = 2 x = 14, i =0, j =11, m = 5 main 3 8 12 15 20 32 44 52 75 100 105 117 0 1 2 3 4

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## 4. Recursion - MATH 224 Discrete Mathematics Recursive C+...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online