-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.c
128 lines (118 loc) · 1.97 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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct ar
{
int n;
int a[100];
};
void getdata(struct ar *l)
{
int z;
printf("\nYou can enter Maximum 100 Data.\nHow many number of data You Want to enter : ");
scanf("%d",&z);
l->n = z-1;
printf("\nRandom Data : ");
srand(time(0));
int i = 0;
while(i < z)
{
//scanf("%d",&l->a[i]);
l->a[i] = rand()%100;
printf("%d ",l->a[i]);
i++;
}
}
int sortdata(struct ar *l)
{
int min,temp,flag;
int i=0;
while(i<l->n)
{
min=i;
flag=1;
int j=i+1;
while(j<=l->n)
{
if(l->a[min] > l->a[j])
{
min = j;
}
if (l->a[j-1] > l->a[j])
{
flag = 0;
}
j++;
}
if(flag == 1)
{
return 0;
}
temp = l->a[i];
l->a[i] = l->a[min];
l->a[min] = temp;
i++;
}
return 0;
}
void printdata(struct ar *l)
{
printf("\nSorted data : ");
int i=0;
while(i<=l->n)
{
printf(" %d",l->a[i]);
i++;
}
printf("\n");
}
void BSearch(struct ar *l)
{
int target;
int count=0;
printf("\nEnter Data You Want to Search : ");
scanf("%d",&target);
int low = 0;
int high = l->n;
printf("\nPath To Search : ");
while(high >= low)
{
count++;
int mid = (high+low)/2;
if(l->a[mid] == target)
{
printf("%d\n",l->a[mid]);
printf("\nTarget Found at Index %d.",mid+1);
break;
}
else if(l->a[mid] > target)
{
printf("%d ->",l->a[mid]);
high = mid-1;
}
else
{
printf("%d ->",l->a[mid]);
low = mid+1;
}
}
if(high<low)
{
printf(" Not Found\nData not Found.");
}
printf("\nThere would %d steps taken to find Target.",count);
}
void main()
{
clock_t t;
struct ar l;
t=clock();
getdata(&l);
sortdata(&l);
printdata(&l);
BSearch(&l);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC;
printf("\nBinary Search took %f seconds to execute \n", time_taken);
printf("\n\n\n");
}