-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinarysearch.c
56 lines (51 loc) · 1 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
55
56
#include <stdio.h>
#include <stdlib.h>
int binary(int *vet, int el, int size)
{
int start = 0;
int final = size-1;
int mid;
while (start <= final)
{
mid = final+start/2;
if (el == vet[mid])
{
return mid;
}
if (el < vet[mid])
{
final = mid-1;
}
else
{
start = mid+1;
}
}
return -1;
}
int main()
{
FILE *myFile;
myFile = fopen("list.txt", "r");
int *array;
int i, size, result, x;
printf("insert array size.\n");
scanf("%d", &size);
array = malloc(size*sizeof(int));
for (i = 0; i < size; i++)
{
fscanf(myFile, "%d", &array[i]);
}
printf("insert the element that you want to find\n");
scanf("%d", &x);
result=binary(array, x, size);
if(result==-1)
{
printf("not found.\n");
}
else
{
printf("the element %d is at %d position\n", array[result], result);
}
return 0;
}