A file is a collection of records and a record is in turn a collection of
fields. A field,which is used to differentiate among various records, is
known as a ‘key’.
Algorithm
Here, m represents the unordered array of elements
n represents number of elements in the array and
el represents the value to be searched in the list
Step 1: [Initialize]
k=0
flag=1
Step 2: Repeat step 3 for k=0,1,2…..n-1
Step 3: if (m[k]=el )
then
flag=0
print “Search is successful” and element is found at location (k+1)
stop
endif
Step 4: if (flag=1) then
print “Search is unsuccessful”
endif
/*Program for Linear Search*/
/*Header Files*/
#include <stdio.h>
#include <stdlib.h>
/*Global Variables*/
int search;
int flag;
/*Function Declarations*/
int input(int *, int, int);
void linear_search(int *, int, int);
void display(int *, int);
/*Functions */
void linear_search(int m[], int n, int el) {
int k;
flag = 1;
for (k = 0; k < n; k++) {
if (m[k] == el) {
printf("\nSearch is Successful");
printf("\nSearch is Successful2");
printf("Element : %i Found at location :%i", el, k + 1);
flag = 0;
}
}
if (flag == 1) {
printf("\n Search is unsuccessful");
}
}
void display(int m[], int n)
{
int i = 0;
for (i = 0; i < 20; i++)
{
printf("\n%d", m[i]);
}
}
int input(int m[], int n, int el)
{
int i;
n = 20;
el = 83;
printf("Number of elements in the list : %d", n);
for (i = 0; i < 20; i++)
{
m[i] = rand() % 100;
}
printf("\n Element to be searched :%d", el);
search = el;
return n;
}
/*Main Function*/
void main()
{
int n, el, m[200];
int number = input(m, n, el);
el = search;
printf("\n Entered list as follows: \n");
display(m, n);
linear_search(m, number, el);
printf("\n In the following list\n");
display(m, n);
}
0 Comments