EmbLogic's Blog

binarysearch using pointers

#include<stdio.h>
2 #include<stdlib.h>
3 int input(int,int *);
4 int search(int *,int,int);
5 int main()
6 {
7
8         int size=10;
9         int * ptr;
10         int i,c,s,key;
11         ptr=(int*)malloc(sizeof(int)*size);
12         c=input(size,ptr);
13         printf(“\n matrix printed are:”);
14         for(i=0;i<size;i++)
15         {
16                 printf(“elements are :%d\n”,*(ptr+i));
17         }
18          printf(“\n enter the element to be searched\n”);
19          scanf(“%d”,&key);
20         s=search(ptr,size,key);
21         printf(“key is %d”,s);
22 return 0;
23 }
24 int input(int size,int *ptr)
25 {
26 int i;
27 printf(“\n enter the matrix”);
28         for(i=0;i<size;i++)
29         {
30                 scanf(“%d”,&(*(ptr+i)));
31         }
32 }
33 int search(int *ptr,int size,int key)
int search(int *ptr,int size,int key)
34 {
35          int l=0,h=size-1,m;
36          while(l<=h)
37          {
38                 m=(l+h)/2;
39                 if(key==*(ptr+m))
40                 {
41                         printf(“element is found at %d element is %d”,m+1,key);
42                         break;
43                 }
44                 else if(key>*(ptr+m))
45                 {
46                         l=m+1;
47                 }
48                 else if(key< *(ptr+m))
49                 {
50                         h=m-1;
51                 }
52                 if(l>h)
53                 {
54                         printf(“element not found”);
55                         break;
56                 }
57         }
58         return key;
59 }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>