Linear Search Algorithm

linear search is a search algorithm, also known as sequential search,that is suitable for searching a list of data for a particular value.It operates by checking every element of a list one at a time in sequence until a match is found.The Linear Search, or sequential search, is simply examining each element in a list one by one until the desired element is found. The Linear Search is not very efficient. If the item of data to be found is at the end of the list, then all previous items mustbe read and checked before the item that matches the search criteria is found.This is a very straightforward loop comparing every element in the array with the key. As soon as an equal value is found, it returns. If theloop finishes without finding a match, the search failed and -1 is returned.For small arrays, linear search is a good solution because it's so straightforward. In an array of a million elements linear search on average willtake500,000 comparisons to find the key. For a much faster search, take a look at binary search.

loop for linear search

int linearSearch(int a[], int first, int last, int key) {
// function:
// Searches a[first]..a[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -1.
// parameters:
// a in array of (possibly unsorted) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -1 if key is not in the array.

for (int i=first; i<=last; i++) {
if (key == a[i]) {
return i;
}
}
return -1; // failed to find key
}
Algorithm

For each item in the database if the item matches the wanted info exit with this item.Continue loop wanted item is not in database

Source code
using System;
class linSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Enter number of elements you want to hold in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-------------------------");
Console.WriteLine("\n Enter array elements \n");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("-------------------------");
Console.WriteLine("Enter Search element\n");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
for(int i=0;i<x;i++)
{
if(a[i]==x2)
{
Console.WriteLine("-------------------------");
Console.WriteLine("Search successful");
Console.WriteLine("Element {0} found at location {1}\n",x2,i+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

1 comments:

lindokuhle said...

nice code..i will b more than happy if u can convert it 2 and b able 2 generate random numbers each time its being implemented

Template by - Mathew | Mux99