Searching
Before writing the algorithm or program for searching , let
us see, “ What is searching? What are the searching techniques?”
Definition : More often we will be working with the large
amount of data. It may be necessary to determine whether a particular item is
present in the large amount of data or not. This process of finding a
particular item in the large amount of data is called searching. The two
important and simple searching techniques are linear search and binary search.
Linear search (Sequential search)
“What is the linear search?”
Definition:
Linear search is a simple searching techniques in which we search for a given
key item in the list in linear order(Sequential order) i.e. one after the
other. The item to be searched is often called key item. The linear search is
also called sequential search.
For example , if key=10 and the list is 20,10,40,25 after
searching we say that key is present . If key =100 after searching we say that
key is not present.
“How to search for an item in a list of elements?” The
procedure is as follows.
Procedure: Assume 10 is the item to be searched in the list
of items 50,40,30,60,10. Observe from above figure that, 10 has to be compared
with a[0], a[1], a[2], a[3], a[4].
But, once the value of I is greater than or equal to 5, it
is an indication that item is not present and display the message “Unsuccessful
Search”.
Note: In general the terminal condition in the for loop
i<5 can be replaced by i<n.
You are already familiar with the algorithm and flowchart of
linear search . Now, the C program for linear search is shown below:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,key,a[20];
printf("Enter the
value of n.");
scanf("%d",&n);
printf("Enter n
values:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter item
to search:");
scanf("%d",&key);
/* Search the key in array */
for(i=o;i<n;i++)
{
if(a[i]==key)
{
printf("item
found");
exit(0);
}
}
printf("Not
found");
}
Output
- Very simple approach
- Works well for small array
- Used to search when the elements are not sorted (not in any order)
Disadvantage of linear search
- Less efficient if the array size is large
- If the elements are already sorted, linear search is not efficient.
Note : When the elements are not sorted and size is very
less, linear search is used . if the elements are sorted , a better method or
technique binary search can be used.
Binary Search in C
Selection Search in C
Binary Search in C
Selection Search in C