Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Linear Search

User image

Published by

sanya sanya

Published at: 31st Jul, 2023
1.255 mins read

In this searching algorithm, each element is sequentially searched until a match is found or the entire array has been traversed. It is applicable to both sorted and unsorted arrays.

Algorithm

1. Compare target element with each element of array starting form 0th index.

2. If the current element matches the target, return the index of the current element.

3. If the current element does not match the target, move to the next element in the list.

4. Repeat steps 1-3 until the target element is found or until the end of the list is reached.

5. If the target element is not found, return false or -1.

Code:

#include

using namespace std;

int linearSearch(int array[], int size, int target) {

for (int i = 0; i < size; i++) {

if (array[i] == target) {

return i; // Return the index of the target element

}

}

return -1; // Target element not found

}

int main() {

int array[] = {4, 2, 7, 1, 5, 3};

int size = sizeof(array) / sizeof(array[0]);

int target = 5;

int index = linearSearch(array, size, target);

if (index != -1) {

cout << "Element " << target << " found at index " << index << endl;

} else {

cout << "Element " << target << " not found in the array" << endl;

}

return 0;

}

Output:

Element 5 found at index 4

Library

WEB DEVELOPMENT

FAANG QUESTIONS