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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
| #include <stdio.h>
int n; //size of array
int BSearch(int *a,int ITEM)
{
int beg=0,end=n-1;
int mid;
while( beg<=end )
{
mid=(beg+end)/2;
if(a[mid]==ITEM)
return mid;
else if( a[mid] < ITEM )
beg=mid+1;
else
end=mid-1;
}
return -1;
}
void SSort(int *a)
{
int i,j,temp;
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
void DEL(int *a, int ITEM)
{
int i;
int pos=BSearch(a, ITEM);
if(pos!=-1)
{
for(i=pos; i<n-1; i++)
a[i]=a[i+1];
n--;
printf("\n Item Deleted. ");
}
else
printf("\n Item not found. ");
}
void INS(int *a, int ITEM)
{
int pos,i;
//Finding the proper position for Sorted Array
if(ITEM>a[n-1])
pos=n;
else if(ITEM<a[0])
pos=0;
else
{
for(i=0; i<n-1; i++)
if(a[i]<=ITEM && a[i+1]>=ITEM)
{
pos=i+1;
break;
}
}
//Shifting of elements to Insert the element.
for(i=n; i>pos; i--)
a[i]=a[i-1];
a[pos]=ITEM;
n++;
printf("\n Item Inserted. ");
}
void Display(int *a)
{
int i;
for(i=0; i<n; i++)
printf(" %d",a[i]);
}
int main()
{
int a[100],ch,pos,ITEM,i;
printf("\n Enter the number of Elements: ");
scanf("%d",&n);
printf("\n Enter the Elements: ");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
do
{
printf("\n ______________________________________ ");
printf("\n MENU:\n");
printf("\n 1. Insert an element. ");
printf("\n 2. Delete an element. ");
printf("\n 3. Search for an element. ");
printf("\n 4. Display elements. ");
printf("\n 0. Exit. ");
printf("\n Your Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: //INSERT
printf("\n Enter the Item to Insert: ");
scanf("%d",&ITEM);
SSort(a);
INS(a,ITEM);
Display(a);
break;
case 2: //DELETE
printf("\n Enter the Item to Delete: ");
scanf("%d",&ITEM);
SSort(a);
DEL(a,ITEM);
Display(a);
break;
case 3: //SEARCH
printf("\n Enter the Item to Search: ");
scanf("%d",&ITEM);
SSort(a);
pos=BSearch(a,ITEM);
if(pos==-1)
printf("\n Item not Found. ");
else
printf("\n Item found at %d position. ",pos+1);
break;
case 4: //DISPLAY
printf("\n The Elements are: ");
SSort(a);
Display(a);
break;
case 0:
printf("\n Exiting... ");
break;
}
}while(ch!=0);
}
|