|
Linear Search in a Range |
|
|
Linear search consists of looking for a particular value in a collection. |
#include <iostream>
using namespace std;
int LinearSearch(const int *Array, const int Size, const int ValToSearch)
{
bool NotFound = true;
int i = 0;
while(i < Size && NotFound)
{
if(ValToSearch != Array[i])
i++;
else
NotFound = false;
}
if( NotFound == false )
return i;
else
return -1;
}
int main()
{
int Number[] = { 67, 278, 463, 2, 4683, 812, 236, 38 };
int Quantity = sizeof(Number) / sizeof(int);
int NumberToSearch = 0;
cout << "Enter the number to search: "; cin >> NumberToSearch;
int i = LinearSearch(Number, Quantity, NumberToSearch);
if(i == -1)
cout << NumberToSearch << " was not found in the collection\n\n";
else
{
cout << NumberToSearch << " is at the " << i+1;
if( i == 0 )
cout<< "st position of the collection\n\n";
else if( i == 1 )
cout<< "nd position of the collection\n\n";
else if( i == 2 )
cout<< "rd position of the collection\n\n";
else
cout<< "th position of the collection\n\n";
}
return 0;
}
Here is an example of running the program:
Enter the number to search: 278 278 is at the 2nd position of the collection Press any key to continue
Here is another example of running the program:
Enter the number to search: 288 288 was not found in the collection Press any key to continue
|
|
| Copyright © 2004-2009 FunctionX, Inc. |
|
|