1. Write a C++ program for function template to linear and binary search of an array.
#include <iostream>
using namespace std;
template <class T>
int LinearSearch(T arr[], int num, T a) {
for (int i = 0; i < num; ++i) {
if (arr[i] == a)
return i;
}
return -1;
}
int main() {
int arr[] = { 6 , 43 ,23 ,6, 12 ,43, 3, 4, 2, 6 };
int num, index, x;
num = sizeof(arr) / sizeof(int); // size of arr
cout << "Integer Array: ";
for (int i = 0; i <num; ++i) cout << arr[i] << ' ';
cout << endl;
cout << "Enter Value you want to search: ";
cin >> x;
index = LinearSearch(arr, num, x);
if (index != -1)
cout << x << " is present in the array at position " << index << endl;
else
cout << x << " is not present in the array \n" << endl;
char charArr[] = { 'A', 'v', 'D', 'R', 'T','u', 'j', 'o' };
char c;
num = sizeof(charArr) / sizeof(char);
cout << "Char Array: ";
for (int i = 0; i < num; ++i) cout << charArr[i] << ' ';
cout << endl;
cout << "Enter character you want to search: ";
cin >> c;
index = LinearSearch(charArr, num, c);
if (index != -1)
cout << c << " is present in the array at position " << index << endl;
else
cout << c << " is not present in the array " << endl;
}
Comments
Leave a comment