/***************************************************************
* Name: Prof. Rafael Orta
* Course: Computer Science & Programming
* Class: CS04225
*****************************************************************
* Purpose: Demonstrate linear search
*****************************************************************/
#include <iostream>
using namespace std;
void linearSearch (const int unOrderedArray[], int target, int aSize, bool& found, int& location, int& noSearches);
int main()
{
int unOrderedArray[]={5,55,21,23,30,31,35,36,40,50,15}; // Array to be searched.
int aSize = 11; // keeps track of the array size
int location = 0; // Keeps tract of the location where the element was found.
int target = 0; // Hold the value of the number to be searched.
int noSearches = 0; // Keeps track of the number of searches.
bool found; // Boolean variable that controls if the number was found or not.
cout << "What is the number you would like to find in the array: ";
cin >> target;
linearSearch (unOrderedArray, target, aSize, found, location, noSearches);
if (found){
cout << "We found the element in position: " << location << " and it took: " << noSearches << " comparisons" << endl;
}
else
cout << "That element is not part of the array," << " and it took: " << noSearches << " comparisons" << endl;
return 0;
}
void linearSearch (const int unOrderedArray[], int target, int sizeA, bool& found, int& location, int& noSearches){
for (int x=0; x < sizeA; x++){
noSearches = noSearches + 1;
if (unOrderedArray[x] == target){
found = true;
location = x;
return;
}
else
found = false;
}
}