Data Structure Implementation Linear Search
Data Structures
A data structure is a particular way of organizing data in a computer so that it can be used effectively.
For example, we can store items with the same data type using the array data structure.
Introduction to Linear Search in Data Structure
One of the very simplest methods to search an element in an array is a linear search. This method uses a sequential approach to search for the desired element in the list. If the element is successfully found in the list, then the index of that element is returned. The search starts from the first element and sequentially proceeds in the forward direction.
Algorithm for Linear Search in Data Structure
The algorithm for linear search is as shown below. It is a straightforward algorithm. Go through it and study it as we shall be building a computer program on the algorithm.
Algorithm:
function linear_search(integer array[], integer n, integer x)
{
integer k;
for (k = 0, k < n, k++)
if (array [k] = x)
return k;
return -1;
}
Example to Implement Linear Search
The program code to implement a linear search is as given below. This program has been written in C programming. Let’s go through the following program to understand how it helps us find the requisite element in the list using the linear search algorithm. Study each and every component of the code properly, including the statements, variables, loops, etc.
Code:
#include <stdio.h>
#include <conio.h>
int linear_search(int arr[], int n, int x)
{
int i;
for(i = 0; i < n; i++)
if(arr[i] == x)
return i + 1;
return -1;
}
void main()
{
int arr[50], n, i, x, res;
printf("Enter the number of elements in array: ");
scanf("%d", &n);
printf("\nEnter the numbers: ");
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("\nEnter the number to be searched: ");
scanf("%d", &x);
res = linear_search(arr, n, x);
if(res == -1)
printf("\n%d does not exist in the array.", x);
else
printf("\n%d is present at position %d in the array.", x, res);
getch();
}
Code Explanation: The above program first asks the user to specify the number of elements in the array along with the elements. It takes up to 50 elements. Once the array is specified, the user is asked to specify the element that needs to be searched in the array in the next step. The program using loop sequentially searches for the desired element. For this task, the function linear_search() has been used as seen in the code.
Comments
Post a Comment