binary search problem

i want the problem to perform the binary search algorithm , to find the index of an element within an array , but the problem that it always inputs "not found" , plz help me
here is the code
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
#include<iostream>
#include<time.h>
using namespace std;
int binarysearch(int arr[],int s,int key)
{
    int low , high , mid;
    low=0;
    high=s-1;
    while(low<=high)
    {
    mid=(low+high)/2;
    if (key==arr[mid])
 { 
    return mid;
}
    
    else if (key<arr[mid])
    high=mid-1;
    else low= mid +1 ;

}
return -1;
}
int main()
{
	
int arr[30];
srand(time(NULL));	
for(int i=0;i<30;i++)
	{
		  arr[i]=rand()%100;
	}
	
		int k;
	for(int i=0;i<30;i++)
	{cout<<arr[i]<<endl;
}
cout<<"enter key"<<endl;
cin>>k;
int result=binarysearch(arr,30,k);
{	if (result>-1)
			cout<<result<<endl;
else cout<<"not found"<<endl;
}
system("pause");
return 0;
}
You forgot to sort the array.
oh yeah , i forgot that binary search requires sorting , how stupid .
Topic archived. No new replies allowed.