-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearchalgorithm.c
117 lines (98 loc) · 1.79 KB
/
searchalgorithm.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
//Searching algorithm
#include <stdio.h>
void main()
{
int ch,a[10],n,x,i,j,temp,flag;
printf("\nSearching Algorithms\n");
printf("~~~~~~~~~ ~~~~~~~~~~");
printf("\nEnter the size of the array : ");
scanf("%d",&n);
printf("Enter the elts : \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nMenu\n~~~~");
printf("\n1.Binary Search");
printf("\n2.Linear Search");
printf("\n3.Exit");
do
{
printf("\n\nEnter your choice : ");
scanf("%d",&ch);
printf("\n");
switch(ch)
{
case 1: //binary search
for(i=0;i<n;i++)
{
for(j=0;j<(n-i-1);j++)
{
if (a[j+1]<a[j])
{
temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted array : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter the elt to search : ");
scanf("%d",&x);
int first=0,last=n-1,mid;
flag=0;
while(first<=last)
{
mid=(first+last)/2;
if(x==a[mid])
{
flag=1;
printf("Elt %d found at position %d",x,mid+1);
break;
}
else if (x>a[mid])
{
first=mid+1;
}
else
{
last=mid-1;
}
}
break;
case 2: //linear search
printf("Array : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter the elt to search : ");
scanf("%d",&x);
flag=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("Elt %d found at position %d",x,i+1);
flag=1;
break;
}
}
if (flag==0)
{
printf("Elt %d is not found\n",x);
}
break;
case 3:
printf("Exiting...\n");
break;
default :
printf("Invalid choice\n");
break;
}
}while(ch!=3);
}