Last active
January 15, 2016 06:47
-
-
Save NickersF/d377bdcf89d9297248d0 to your computer and use it in GitHub Desktop.
Basic linear search function in C++ (static array)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
#include <string> | |
#include <fstream> | |
#include <cmath> | |
#include <cstring> | |
using namespace std; | |
const int ARRAY_SIZE = 7; | |
int seqSearch(const int list[], int listLength, int searchItem); | |
int main() | |
{ | |
int arr[] = { 35, 12, 27, 18, 45, 16, 38 }; | |
int searchNum; | |
int searchResult; | |
cout << "Enter a number to you think is in this array: "; | |
cin >> searchNum; | |
searchResult = seqSearch(arr, ARRAY_SIZE, searchNum); | |
if (searchResult != -1) { | |
cout << "The result " << searchNum << " is located at index #" << searchResult << endl; | |
} | |
else { | |
cout << "The " << searchNum << " is not in the list." << endl; | |
} | |
return 0; | |
} | |
int seqSearch(const int list[], int listLength, int searchItem) { | |
int pos; | |
bool found = false; | |
pos = 0; | |
while (pos < listLength && !found) { | |
if (list[pos] == searchItem) { | |
found = true; | |
} | |
else { | |
pos++; | |
} | |
} | |
if (found) { | |
return pos; | |
} | |
else { | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment