Practical1 CPP
Practical1 CPP
#include <algorithm>
#include <chrono> //library used for clock timing
#include <ctime>
#include <cstdlib>
#include <iomanip>
// Linear Search
int LinearSearch(int arr[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
{
return i;
}
}
return -1;
}
if (arr[mid] == x)
return mid;
else if (arr[mid] > x)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
int main()
{
srand(time(NULL));
int n, arr[MAX];
cout << "Enter the number of elements:";
cin >> n;
for (int j = 0; j < n; j++)
{
arr[j] = rand() % MAX; // Gerneration of Random array numbers
}
for (int j = 0; j < n; j++)
{
cout << arr[j] << "\t"; // Printing the array
}
int x;
cout << "\nEnter the element to search: ";
cin >> x;
// Linear Search
auto startL = chrono::high_resolution_clock::now(); // Starting the clock
int resultL = LinearSearch(arr, n, x);
auto endL = chrono::high_resolution_clock::now(); // Stoping the clock
cout << "\nTime taken by Recursive Binary Search: " << fixed <<
durationL.count() << " microseconds" << endl;