Linear search program in c

Linear search program in c

What is linear search or sequential search : Definition of linear search

As the name linear search or sequential search, search the number one by one in the specified array or list.

linear search or sequential search is a method for finding a target value within a list.

It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.

linear-search
linear-search

Let’s see the simple program to perform linear search:

#include
void main()
{
int a[20], i, item;
printf(“\nEnter 15 elements of an array:\n”);
for (i=0; i<=14; i++)
scanf(“%d”, &a[i]);
printf(“\nEnter item to search: “);
scanf(“%d”, &item);
for (i=0; i<=19; i++) if (item == a[i]) { printf(“\nEntered item found at location %d”, i+1); break; } if (i > 9)
printf(“\n Entered item does not exist.”);
getch();
}

The above program will search the number in the defined array one by one and if find the number this program will output their index location.

Linear search is rarely used as this is slow to search than search algorithms such as the binary search algorithm and hash tables allow significantly faster searching comparison to Linear search.

How linear search algorithm works

linear_search program overview
linear_search program overview

Step 1: Read the search element from the user

Step 2: Compare, the search element with the first element in the list.

Step 3: If both are matching, then display “Given element found!!!” and terminate the function

Step 4: If both are not matching, then compare search element with the next element in the list.

Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in the list.

Step 6: If the last element in the list is also doesn’t match, then display “Element not found!!!” and terminate the function.

 

Leave a Reply