/*!
* file LinearSearchRecursion.cpp
* author Hasan
* date 25 June 2014 00:12:21
*/
#include <iostream>
#include <iomanip>
void printArray3(int[]);
int linearSearch1(int [],int,int,int);
using namespace std;
const int SIZE = 10;
int searchKey,element;
int main(){
int array[SIZE] = { 0 };
for (int i = 0; i < SIZE; i++){
array[i] = i*2;
}
cout << "Array\n";
printArray3(array);
cout << "Enter the integer to search = ";
cin >> searchKey;
element = linearSearch1(array,searchKey,0,SIZE -1);
if (element == -1)
{
cout << "Key not found";
cin.get();
}
else {
cout << "Key found in element " << element;
cin.get();
}
cin.get();
return 0;
}
int linearSearch1(int a[], int sKey, int low, int high){
if (a[low] == sKey)
return low;
else if (low == high)
return -1;
else
return linearSearch1(a, sKey, low + 1, high);
}
void printArray3(int a[SIZE]){
for (int i = 0; i < SIZE; i++){
cout << setw(4) << a[i];
}
cout << endl;
}
output:
Array
0 2 4 6 8 10 12 14 16 18
Enter the integer to search = 12
Key found in element 6
Array
0 2 4 6 8 10 12 14 16 18
Enter the integer to search = 13
Key not found
Post a Comment