Chat history
Open sidebar
ChatGPT
You said:
linear search algorithm examples
ChatGPT said:
ChatGPT
Here are two examples of the Linear Search Algorithm written in Python and C++:
Python Example
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index if the element is found
return -1 # Return -1 if the element is not found
# Example usage
arr = [10, 20, 30, 40, 50]
target = 30
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
C++ Example
#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Return the index if the element is found
return -1; // Return -1 if the element is not found
int main() {
int arr[] = {10, 20, 30, 40, 50};
int target = 30;
int n = sizeof(arr) / sizeof(arr[0]);
int result = linearSearch(arr, n, target);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found" << endl;
return 0;
Explanation of Linear Search:
Linear search goes through each element of the array one by one.
Time Complexity:
Best Case:
O(1) (when the target is found at the first position)
Worst Case:
O(n) (when the target is not present or is at the last position)
Space Complexity:
1
)
O(1)
Is this conversation helpful so far?
ChatGPT can make mistakes. Check important info.