0% found this document useful (0 votes)
2 views

Algorithm search

The document provides examples of the Linear Search Algorithm in Python and C++. It explains how the algorithm works, detailing its time complexity (O(1) best case and O(n) worst case) and space complexity (O(1)). The examples demonstrate how to implement the algorithm and check for the presence of a target element in an array.

Uploaded by

kenyuydzeonline
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Algorithm search

The document provides examples of the Linear Search Algorithm in Python and C++. It explains how the algorithm works, detailing its time complexity (O(1) best case and O(n) worst case) and space complexity (O(1)). The examples demonstrate how to implement the algorithm and check for the presence of a target element in an array.

Uploaded by

kenyuydzeonline
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

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.

You might also like