#include <iostream> #include <iomanip> using namespace std; int linearSearch(const int[],int ,int); int main(){ const int arraySize = 10; int a[arraySize]; int searchKey; //value to locate in array a for (int i = 0; i < arraySize; i++){ a[i] = 2 * i; } for (int i = 0; i < arraySize; i++) cout << setw(4) << a[i]; cout << "\n\nEnter integer search key = "; cin >> searchKey; int element = linearSearch(a, searchKey, arraySize); if (element != -1){ cout << "Found value in element in "<< element <<endl; cin.get(); } else { cout << "Value not found"<<endl; cin.get(); } cin.get(); return 0; } int linearSearch(const int array[], int key, int sizeOfArray){ for (int i = 0; i < sizeOfArray; i++){ if (array[i] == key){ return i; } } return -1; }output:0 2 4 6 8 10 12 14 16 18 Enter integer search key = 12 Found value in element in 60 2 4 6 8 10 12 14 16 18 Enter integer search key = 17 Value not found
Monday, 2 March 2015
Linear Search C++
Subscribe to:
Post Comments (Atom)
Nice work..Keep it up!
ReplyDelete