forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_search.c
88 lines (62 loc) · 1.33 KB
/
random_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
It is a monte carlo version of code with a depth,it give you the optimal or sub optimal result
*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int pick_random(int *a,int n){
int i;
time_t t;
srand((unsigned)time(&t));
return a[rand()%n];
}
int* create(int n){
int* a = (int*)malloc(n*sizeof(n));
for (int i = 0; i < n; i++)
{
/* code */
scanf("%d",(a+i));
}
return a;
}
void display(int *a,int n){
for (int i = 0; i < n; i++)
{
/* print the array */
printf("%d ",*(a+i));
}
}
int random_search(int element,int *a,int n){
int set_depth = 1000;
while (1 || set_depth<1000)
{
/* infinite loop untill get the element */
int temp = pick_random(a,n);
if (temp == element)
{
return 1;
break;
}
set_depth++;
}
return 0;
}
int main(int argc, char const *argv[])
{
int n;
printf("enter the size of the array:");
scanf("%d",&n);
int *a = create(n);
display(a,n);
int element;
printf("enter the element to search:");
scanf("%d",&element);
if(random_search(element,a,n)==1){
printf("element found");
}
else
{
printf("element not found");
}
return 0;
}