-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBSEARCH_ITR.C
106 lines (47 loc) · 4.32 KB
/
BSEARCH_ITR.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* BINARY SEARCH- ITERATIVE APPROACH */
#include<stdio.h>
#include<conio.h>
void main()
{
int n, arr[50], first, mid, last, key, loc, i;
int flag=0;
clrscr();
printf("\nEnter number of elements: ");
scanf("%d", &n);
printf("\nEnter the elements: ");
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
first=0;
last=n;
printf("\nEnter the element to be searched: ");
scanf("%d", &key);
while(first<=last)
{
mid=(first+last)/2;
if(arr[mid]==key)
{
flag=1;
printf("\nElement found at location %d", mid+1);
break;
}
else if(key>arr[mid])
first=mid+1;
else
last=mid-1;
}
if(flag==0)
printf("\nElement not found");
getch();
}
/* OUTPUT-1
Enter number of elements: 5
Enter the elements: 1 3 4 6 7
Enter the element to be searched: 4
Element found at location 3
*/
/* OUTPUT-2
Enter number of elements: 5
Enter the elements: 1 3 4 6 7
Enter the element to be searched: 5
Element not found
*/