二分查找练习

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
#include <iostream>
 
using namespace std;
 
int arr1[] = { 1,2,3,4,5,6,7,8,9 };
int arr2[] = { 1,1,1,2,3,3,4,6,98 };
 
int MyBinarySearch(int array[], int begin, int end, const int value)
{
    while (begin <= end)
    {
        int middle = (begin + end) / 2;
        if (value > array[middle])
            return MyBinarySearch(array, (middle+1), end, value);
        else if (value < array[middle])
            return MyBinarySearch(array, 0, (middle-1), value);
        else
            return middle;
    }
    return -1;
}
 
int  MyBinarySearch1(int array[], int length,const int value)
{
    int begin = 0;
    int end = length - 1;
    while (begin <= end)
    {
        int middle = (begin + end) / 2;
        if (value == array[middle])
            return middle;
        else if (value > array[middle])
            begin = middle + 1;
        else
            end = middle - 1;
    }
 
    return -1;
}
 
 
int main()
{
    cout << MyBinarySearch(arr1, 0, 8, 7) << endl;
    cout << MyBinarySearch(arr2, 0, 8, 98) << endl;
    cout << MyBinarySearch(arr1, 0, 8, 1) << endl;
    cout << MyBinarySearch(arr2, 0, 8, 1) << endl;
    cout << endl;
    cout << MyBinarySearch(arr1, 0, 8, 77) << endl;
    cout << MyBinarySearch(arr1, 0, 8, 0) << endl;
    cout << MyBinarySearch(arr2, 0, 8, 7) << endl;
    cout << MyBinarySearch(arr2, 0, 8, 99) << endl;
    cout << MyBinarySearch(arr2, 0, 8, 0) << endl;
    cout << endl;
 
    cout << MyBinarySearch1(arr1, 9, 7) << endl;
    cout << MyBinarySearch1(arr2, 9, 98) << endl;
    cout << MyBinarySearch1(arr1, 9, 1) << endl;
    cout << MyBinarySearch1(arr2, 9, 1) << endl;
    cout << endl;
    cout << MyBinarySearch1(arr1, 9, 77) << endl;
    cout << MyBinarySearch1(arr1, 9, 0) << endl;
    cout << MyBinarySearch1(arr2, 9, 7) << endl;
    cout << MyBinarySearch1(arr2, 9, 99) << endl;
    cout << MyBinarySearch1(arr2, 9, 0) << endl;
    cout << endl;
 
 
    return 0;
}

  

posted on   itdef  阅读(374)  评论(0编辑  收藏  举报

努力加载评论中...

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示