summaryrefslogtreecommitdiff
path: root/chapter12/search.cxx
blob: c5ff8818375e98b9fc7e7d5772574f008e5ca114 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// FILE: search.cxx
// Demonstration program for the binary search function

#include <cstdlib>    // Provides EXIT_SUCCESS, size_t
#include <iostream>   // Provides cin, cout
using namespace std;

// PROTOTYPE for function used in demonstration program:
void search(
    const int a[ ],
    size_t first,
    size_t size,
    int target,
    bool& found,
    size_t& location
);


int main( )
{
    const size_t MANY = 10;
    int fibonacci[MANY] = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
    int target;
    bool found;
    size_t location;

    do
    {
        cout << "Please type an integer from 0 to 100: ";
        cin >> target;
    }
    while ((target < 0) || (target > 100));
    search(fibonacci, 0, MANY, target, found, location);

    if (found)
        cout << target << " is a Fibonacci number at ["
             << location << "] in my array." << endl;
    else
        cout << target << " is not a Fibonacci number." << endl;

    return EXIT_SUCCESS;
}
    
void search(
    const int a[ ],
    size_t first,
    size_t size,
    int target,
    bool& found,
    size_t& location
)
// Precondition: The array segment starting at a[first] and containing size
// elements is sorted from smallest to largest.
// Postcondition: The array segment starting at a[first] and containing size
// elements has been searched for the target. If the target was present, then
// found is true, and location is set so that target == a[location]; 
// Otherwise, found is set to false.
// Library facilities used: stdlib.h (provides size_t).
{
    size_t middle;

    if (size == 0)
        found = false;
    else
    {
        middle = first + size/2;
        if (target == a[middle])
        {
            location = middle;
            found = true;
        }
        else if (target < a[middle])
            // The target is less than a[middle], so search before the middle
            search(a, first, size/2, target, found, location);
        else 
            // The target must be greater than a[middle], so search after the middle
            search(a, middle+1, (size-1)/2, target, found, location);
    } 
}