Custom Search

 

 

 

 
 

 

Linear Search


Binary Search | Bubble Sort | Selection Sort | Finding Maximum Value | Linear Search | Celsius to Fahrenheit | 10 Pseudo-random numbers | Calculating Average | Swapping Values | Lowercase/ Uppercase

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 must be read and checked before the item that matches the search criteria is found.


Program for Searching an item in the list using Linear Search

 

C++ Source Code

#include <iostream.h>

int LinearSearch(int [], int, int);

int main()
{
const int NUMEL = 10;
int nums[NUMEL] = {5,10,22,32,45,67,73,98,99,101};
int item, location;


cout << "Enter the item you are searching for: ";
cin >> item;

location = LinearSearch(nums, NUMEL, item);

if (location > -1)
cout << "The item was found at index location " << location
<< endl;
else
cout << "The item was not found in the list\n";

return 0;
}

// this function returns the location of key in the list
// a -1 is returned if the value is not found
int LinearSearch(int list[], int size, int key)
{
int i;

for (i = 0; i < size; i++)
{
if (list[i] == key)
return i;
}

return -1;
}

 

See Also


                        

 

 

 

Custom Search
 

Home      Disclaimer      Advertise      Contact      Privacy Policy     

Copyright 2004-15 Paked.com. All rights reserved.

Note: Site best viewed at 1024 x 768 or higher screen resolution