Binary Search is drunk

My binary search function is drunk. Some numbers work, some don't. I believe the problem lies in the binsearch function.

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <math.h>

using namespace std;

int binsearch(int arrray[],int element);
void fill(int arrray[]);
void display(int arrray[]);
void sort(int arrray[]);

	int main()

{
	int window;
	int num;
	int result;
	int arrray[20];

	fill(arrray);

	display(arrray);
	
	sort(arrray);

	cout << "\n" << endl;

	display(arrray);

		cout << "\n" << endl;

	cout << "What element are you searching for\?" << endl;
	cin >> num;

	result = binsearch(arrray,num);

	if (result != -1)
		cout << "\nThe element was found at index " << result << "." << endl;
	else
		cout << "\nThe number was not found." << endl;

	cin >> window;

return 0;

}

void fill(int arrray[])
{
	srand(1);
		for(int i = 0; i < 20; i++)
		{
			arrray[i] = rand() % 100;
		}
}

int binsearch(int arrray[],int element)
{
	int position;
	int max = 19;
	int min = 0;

       position = (20) / 2;

       while((arrray[position] != element) && (min <= max))
       {
              if (arrray[position] > element)             
             {                                         
                    max = position - 1;    
             }                                                      
             else                                                
            {                                    
                   min = position + 1;     
            }
             position = (min + max) / 2;
       }
      if (min <= max)
      {
        return max;
      }      
       else
        return -1;
}

void display(int arrray[])
{
	int num;
	int result;

	for(int x = 0; x < 20; x++)
		cout << arrray[x] << "  ";

}

void sort(int arrray[])
{
     int i, j, key, numLength = 20;
     for(j = 1; j < numLength; j++)
    {
           key = arrray[j];
           for(i = j - 1; (i >= 0) && (arrray[i] > key); i--)
          {
                 arrray[i+1] = arrray[i];
          }
         arrray[i+1] = key;
     }
     return;
}
Shouldn't you return position instead of max?
Topic archived. No new replies allowed.