Presentation is loading. Please wait.

Presentation is loading. Please wait.

RECURSION Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian

Similar presentations


Presentation on theme: "RECURSION Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian"— Presentation transcript:

1 RECURSION Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian bhajian@scs.carleton.ca

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23 Graphical Examples

24

25

26

27

28

29

30

31

32

33

34

35 Search Examples

36

37 The Binary Search Algorithm  The binary search algorithm is naturally recursive.  That is, the action that we perform on the original list is the very same as the action that we perform on the sublists.  As a consequence, it is very easy to write a recursive binary search function.

38

39

40 The BinarySearch() Function int BinarySearch(int a[], int value, int left, int right) { // See if the search has failed if (left > right) return –1; // See if the value is in the first half int middle = (left + right)/2; if (value < a[middle]) return BinarySearch(a, value, left, middle – 1); // See if the value is in the second half else if (value > a[middle]) return BinarySearch(a, value, middle + 1, right); // The value has been found else return middle; }

41 The BinarySearch() Function  The signature of the preceding function is (int a[], int value, int left, int right)  This means that the initial function call would have to be BinarySearch(a, value, 0, size – 1);  However, that is not the standard interface for a search function.

42 The BinarySearch() Function  Normally, the function call would be written as BinarySearch(a, size, value);  Therefore, we should write an additional BinarySearch() function with prototype int BinarySearch(int a[], int size, int value);  This function will call the other one and then report back the result.

43

44

45

46

47


Download ppt "RECURSION Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian"

Similar presentations


Ads by Google