-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search.c
More file actions
39 lines (35 loc) · 881 Bytes
/
binary search.c
File metadata and controls
39 lines (35 loc) · 881 Bytes
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
#include<stdio.h>
int binarysearch(int arr[],int left,int right,int target)
{
while(left <= right)
{
int mid = left + (right-left)/2;
if (arr[mid] == target)
return mid;
if (arr[mid]< target)
left = mid + 1;
else
right = mid-1;
}
return -1;
}
int main()
{
int n;
printf("Enter the number of elements :");
scanf("%d",&n);
int arr[n];
printf("Enter %d sorted elements :",n);
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
int size =n;
int target;
printf("Enter the Number to search : ");
scanf("%d",&target);
int result = binarysearch(arr,0,size-1,target);
if (result!=-1)
printf("Element found at index %d\n",result);
else
printf("Element not found in the array \n");
return 0;
}