Binary search help

Hi,

I've been given a simple task of outputting the middle item from a given data. The data is already sorted. I created a code which compiled successfully yet produces no output. I'm wondering if someone can spot the mistake in my code. Thank you in advance.



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
  #include <iostream>
#include <vector>
using namespace std;

int BinarySearch(vector<int> vect1, int size)
{
    int mid;
    int low;
    int high;

    low = 0;
    high = size - 1;
    mid = (high + low) / 2;

    while(low <= high)
    {
        if (mid == vect1[mid])
        {
            return mid;
        }
        else if (mid > vect1[mid])
        {
            low = mid + 1;
        }
        else
            {
            high = mid - 1;
            }
    }


    return -1; // not found
}

int main() {

    int size = 5;
    vector<int> vect1(size);
    int middleNumber;

    //Fill vector
    for (int i = 0; i < vect1.size(); ++i) {
        cin >> vect1.at(i);
    }


   middleNumber = BinarySearch(vect1, size);

    cout << middleNumber;
    return 0;
}
You are mixing things. There is no "search" involved.

Middle item is a question: "What is the value of the item that is in the middle?"
4 7 9

What is in the middle?

The array has 3 elements. There is a middle element. Its index is 1 and value 7.
Surprisingly, 3/2 == 1. Is this (array size / 2 is in the middle) true for all arrays?

2 4 6 7 8 9

The array has 6 elements. 6/2==3. Element index 3 has value 7.
Alas, since the array has even number of elements, the 7 is not exactly middle.
If you were looking for median, you would say either "6 and 7",
or (6+7)/2.0, i.e. 6.5.

Every array has median.


Binary search is a question:
"Does the array have value X? If yes, then which item has value X?"
The answer could be any item of the array, or none.

Binary search uses the knowledge that the array is sorted to reduce computation.
You don't have any value to search.
Topic archived. No new replies allowed.