A program to implement the linear search algorithm.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int linear_search(const int *p, const int val, const int sz);

int main(void)
{
int arr[100], val, n, pos;

printf("\nPopulating the array randomly. Please wait....");

randomize();

for(n = 0 ; n < 100 ; n++)
arr[n] = rand() % 100;

printf("....Done");

//for(n = 0 ; n < 100; n++)
//printf("%d\t",arr[n]);

printf("\nEnter value to search : ");
scanf("%d", &val);

pos = linear_search(arr, val, 100);
if(pos)
printf("\n%d was found at the %dth position", val, pos);
else
printf("\n%d was NOT found in the array", val);

return 0;

}

int linear_search(const int *p, const int val, const int sz)
{
int n = 0;
for(n = 0 ; n < sz ; n++)
{
if(p[n] == val)
return (n + 1);
}
return 0;
}

No comments:

Post a Comment

kiss on google ads if you are anonymous because your ip is trackable.thank you.

......from.admin