Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursive Binary Search

Similar presentations


Presentation on theme: "Recursive Binary Search"— Presentation transcript:

1 Recursive Binary Search
L. Grewe

2 The Binary Search Algorithm
is naturally recursive. the action that we perform on the original list is the very same as the action that we perform on the sublists. easy to write a recursive binary search function.

3 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; }

4 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.

5 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.

6 The BinarySearch() Function
int BinarySearch(int a[], int size, int value) { return BinarySearch(a, value, 0, size – 1); }

7 A Recursive Sequential Search
A sequential search may also be written recursively. As before, we will write two versions. The “public” version with the standard interface. The “private” version with the recursive interface.

8 The SequentialSearch() Function
int SequentialSearch(int a[], int size, int value) { return SequentialSearch(a, value, 0, size); }

9 The BinarySearch() Function
int SequentialSearch(int a[], int value, int start, int stop) { // See if the search has failed if (start >= stop) return –1; // See if the value has been found else if (a[start] == value) return start; // Otherwise, continue the search else return SequentialSearch(a, value, start + 1, stop); }


Download ppt "Recursive Binary Search"

Similar presentations


Ads by Google