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

1 Linear - Search

m

Uploaded by

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

1 Linear - Search

m

Uploaded by

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

Pseudocode of Linear Search

Function LinearSearch(array, targetValue):


For i from 0 to length(array) - 1:
If array[i] = targetValue:
Return i // Return the index where
targetValue is found
EndFor
Return -1 // Return -1 if targetValue is not
found in the array

Explanation:
 The function LinearSearch takes in two parameters: an array and a
targetValue that we want to search for.
 It iterate over the array from the first to the last element.
 For each element, we check if it matches the targetValue.
 If a match is found, we return the index [i] where the match occurred.
 If no match is found after scanning the entire array, we return -1 to indicate
that the targetValue is not present in the array.

CODE in C++ for Linear Search


#include <iostream>
#include <vector>
int linearSearch(const std::vector<int>& array, int targetValue) {
for (int i = 0; i < array.size(); i++) {
if (array[i] == targetValue) {
return i; // Return the index where targetValue is found
}
}
return -1; // Return -1 if targetValue is not found in the array
}
int main() {
std::vector<int> array = {1, 3, 5, 7, 9, 11, 13, 15};
int target;

std::cout << "Enter the number to search for: ";


std::cin >> target;

int result = linearSearch(array, target);


if (result != -1) {
std::cout << "Value found at index: " << result << std::endl;
} else {
std::cout << "Value not found in the array." << std::endl;
}
return 0;
}
Time complexity of Linear Search
Best Case # O (1)
Worst Case # O ( n )
Average Case # O ( n/ 2)

You might also like