Experiment 3
Experiment 3
Linear Search :-
Algorithm –
1. Start
2. Input: Read n (size of array).
3. Declare: Create an array of size n.
4. Input Elements: Read n elements into the array.
5. Input: Read v (item to be searched).
6. Search:
o For each element in the array:
If the element = v, print its position and increment x.
7. Check Result:
o If x is 0, print “Item not found”.
o Else, print “Search successful”.
8. End
Code -
int main(){
int n , x=0;
printf("Enter the size of array : ");
scanf("%d",&n);
int array [n];
printf("Enter the elements of the Arrays :\n");
for (int i=0;i<n;i++){
scanf("%d",&array[i]);
}
int v;
printf("Enter the Item to be Searched : ");
scanf("%d",&v);
1
for (int j=0;j<n;j++){
if (array[j]==v){
printf("Item %d found at %d Position",v,j+1);
x++;
}
}
if (x==0){
printf("\nSearch unsuccessful Item Not Found.");
}
else {
printf ("\nItem found Search successful");
}
return 0;
}
Output-
Applications:-
-Finding Contact Information
Linear search can be found in applications where users need to search for specific contact
information, such as in a phone book or contact list.
-Searching for Files
When you perform a search for a file by name on your computer or within a folder, the
system may use linear search to scan through the directory until it finds the desired file.
2
Binary Search:-
Algorithm-
1. Input:
o Read the size of the list (n).
o Read n elements into the array list.
o Read the item to be searched (s).
2. Initialize:
o Set B (beginning) to 1.
o Set E (end) to n.
o Set done to 0.
3. Binary Search:
o While B <= E:
Calculate Mid as (B + E) / 2.
If list[Mid] == s:
Print position (Mid + 1).
Set done to 1.
Break.
If list[Mid] < s:
Set B to Mid + 1.
Else:
Set E to Mid - 1.
4. Result:
o If done == 0, print “Search is unsuccessful”.
o Else, print “Search is successful”.
3
Code-
#include<stdio.h>
int main(){
int a , n ,done=0;
printf("Enter the size of list :");
scanf ("%d",&n);
int list [n];
printf ("Enter the elements in the list :");
for (a=0;a<n;a++){
scanf("%d",&list[a]);
}
printf ("Enter the item to be searched ");
int s;
scanf("%d",&s);
printf("Item is %d", s);
int B=1,E=n,Mid;
int item = s;
while(B<=E){
Mid = (E+B)/2;
if(list[Mid]==item){
printf("\nItem found in %d ",Mid +1);
done = 1;
break;
}
if (list[Mid]<item){
B=Mid+1;
}
else{
E=Mid-1; }
4
}
if (done=0){
printf("\nSearch is unsuccessful");
}
else {
printf("\nSeacrh is successful");
}
return 0;
}
Output-
Applications:-
-Searching in sorted arrays: Binary search is used to efficiently find an element in a sorted
array.
-Database queries: Binary search can be used to quickly locate records in a database table
that is sorted by a specific key