-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.c
54 lines (51 loc) · 1.17 KB
/
BinarySearch.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
#include <stdio.h>
#include <stdlib.h>
int BinarySearchRecursive(int*, int, int, int);
int BinarySearchIterative(int*, int, int, int);
int main() {
int n,key,keyTwo;
printf("Enter the number of elements : ");
scanf("%d",&n);
int* p = (int *)malloc(n * sizeof(int));
for(int i = 0; i < n; i++) {
scanf("%d",&p[i]);
}
/*for(int i = 0; i < n; i++) {
printf("%d",p[i]);
}*/
//Assumption array is already sorted
printf("\nEnter the element to search for : ");
scanf("%d",&key);
int position = BinarySearchRecursive(p,0,n,key);
printf("\n%d\n",position);
scanf("%d",&keyTwo);
int position2 = BinarySearchIterative(p,0,n,keyTwo);
printf("\n%d\n",position2);
return 0;
}
int BinarySearchRecursive(int *a, int l, int d, int key) {
if(l > d) {
return -1;
}
int mid = (l+d)/2;
if(a[mid] == key){
return mid + 1;
}else if(a[mid] < key){
return BinarySearchRecursive(a, mid+1, d, key);
}else{
return BinarySearchRecursive(a, l, mid-1, key);
}
}
int BinarySearchIterative(int *a, int l, int d, int key) {
while(l <= d) {
int mid = (l+d)/2;
if(a[mid] == key) {
return mid+1;
}else if(a[mid] < key) {
l = mid + 1;
}else {
d = mid - 1;
}
}
return -1;
}