Searching Problem

This is the problem of finding the given key element in a list of elements. When the key element is found in the list we call Search as Successful Search otherwise Unsuccessful Search. Two simple Searching Methods which are commonly used are:
• Linear / Sequential Search
• Binary Search
Linear / Sequential Search

It compares each elements of the array with key element Sequentially / Linearly(one element at a time) and it STOPS when Key is Found and declare Successful Search, It also STOPS when Array exhaust and declare Unsuccessful Search. The algorithm of Linear/Sequential Search is:

Algorithm : Linear_Search( )
Begin
read the number of elements n
read n elements of an array a
read the key element to be searched
flag = FALSE // Assume key is not found
for i = 0 to n-1 do //compare key with all the elements
if a[i] == key then
flag = TRUE break
end if
end for
if flag == TRUE then
print “Successful Search”
else
print “UnSuccessful Search”
end if

Example: Program to find given key element in an array of n integer elements using Linear Search
int main ()
{ int a[50], n, min, i, flag = 0;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 1 = n = 50 */
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”, &a[i]);
printf(“\n\tEnter the Key element to be Searched: “);
scanf(“%d”, &key);
for (i = 0; i < n; i++ )
{ if(a[i] == key)
{
flag = 1; break;
}
}
if( flag == 1)
printf(“Successful Search - Key found ”);
else
printf(“Unsuccessful Search - Key NOT found”);
return 0;
}
Searching Problem Searching Problem Reviewed by Unknown on 04:53 Rating: 5

No comments:

Powered by Blogger.