0% found this document useful (0 votes)
31 views1 page

Linear Search

The document contains a C++ program that implements a linear search algorithm to find an element in an array. It prompts the user to input the size of the array and its elements, then searches for a specified target element while measuring the execution time. The program outputs the index of the found element or indicates if it is not present, and it also cleans up dynamically allocated memory.

Uploaded by

kimajam628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views1 page

Linear Search

The document contains a C++ program that implements a linear search algorithm to find an element in an array. It prompts the user to input the size of the array and its elements, then searches for a specified target element while measuring the execution time. The program outputs the index of the found element or indicates if it is not present, and it also cleans up dynamically allocated memory.

Uploaded by

kimajam628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <iostream>

#include <chrono>
using namespace std;
using namespace std::chrono;

// Linear Search function


int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;

int* arr = new int[size];


cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

int target;
cout << "Enter the element to search: ";
cin >> target;

// Measure execution time


auto start = high_resolution_clock::now();
int result = linearSearch(arr, size, target);
auto end = high_resolution_clock::now();
auto duration = duration_cast<nanoseconds>(end - start);

// Output result
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in the array" << endl;
}
cout << "Execution time: " << [Link]() << " nanoseconds" << endl;

// Clean up dynamic memory


delete[] arr;
return 0;
}

You might also like