Linear Search in C language
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, a, a, a, a.
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:
printf("Enter the value of n.");
printf("Enter n values:\n");
printf("Enter item to search:");
/* Search the key in array */
- 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.