forked from piyush-kash/Hacktober2021-cpp-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearchwithpointers.c
More file actions
48 lines (41 loc) · 1.03 KB
/
binarysearchwithpointers.c
File metadata and controls
48 lines (41 loc) · 1.03 KB
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
// A binary search C program using pointers.
#include<stdio.h>
int binarysearch(int *arr, int ele, int *ptrlast, int **ptr_to_value);
void main()
{ int arr[20],n,i;
int found,value;
int *ptrlast,*ptr_to_value;
int ele;
ptr_to_value=NULL;
printf("Enter the number of elements");
scanf("%d",&n);
printf("Enter the elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Enter the element to be searched");
scanf("%d",&ele);
ptrlast=arr+n-1;
found=binarysearch(arr,ele,ptrlast,&ptr_to_value);
found?printf("Element %d is found",*ptr_to_value):printf("Element is not found");
}
int binarysearch(int *arr, int ele, int *ptrlast, int **ptr_to_value)
{ int *firstptr, *midptr, *lastptr;
firstptr=arr;
lastptr=ptrlast;
while(firstptr<=lastptr)
{ midptr = firstptr+(lastptr-firstptr)/2;
if(ele>*midptr)
{ firstptr=midptr+1;
}
else if(ele<*midptr)
{
lastptr=midptr-1;
}
else
{
firstptr=lastptr+1;
}
}
*ptr_to_value=midptr;
return(ele==*midptr);
}