-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array_Binary_Search.c
68 lines (53 loc) · 1.13 KB
/
Array_Binary_Search.c
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
/*******
Author: Noel Toy
Date: 21/03/2018
Contact:noeltoy21@gmail.com
Discription: This program will take the array values from the user and allows to user to search an element. If the element is found the algoritm will return the index.
Prerequisite: Array should be in sorted order
********/
#include<stdio.h>
int binary_serach(int a[],int low,int up,int item);
void main()
{
int a[10],i,item,up,pos;
printf("Enter the number of elements in array:");
scanf("%d",&up);
printf("Enter the elements to the array:\n");
for(i=0;i<up;i++)
{
printf("Enter value for a[%d]:",i);
scanf("%d",&a[i]);
}
printf("\nEnter the item to be searched:");
scanf("%d",&item);
pos= binary_serach(a,0,up-1,item);
if(pos==-1)
{
printf("The Item Not Found!!\n");
}
else
{
printf("The Item found at position %d\n",pos+1);
}
getch();
}
int binary_serach(int a[],int low,int up,int item)
{
if(up>=low)
{
int mid=(up+low)/2;
if(a[mid]==item)
{
return mid;
}
if(item<a[mid])
{
return binary_serach(a,low,mid-1,item);
}
return binary_serach(a,mid+1,up,item);
}
else
{
return -1;
}
}