Linear Search
Search an element in an Array:
Searching an element in an array is basically searching any number in the given array and if the element is found in the array then return its index in the array.
There are multiple algorithms to search an element in an array. I will cover each algorithm one by one.
Linear Search:
In Linear search, we have to compare the Key/Element to each element of the array, below is the program for Linear search in c++.
#include <iostream>
using namespace std;
/**
* @brief The Array struct: Structure Which Contains array of size 10 and array's* Length (number of items it contains.)*/struct Array{int A[10];int iLength;};/**
* @brief LinearSearch: This methods search the Key in the array passed in first param.* @param objArr: object of Struct Array, Which contains array and Length of the array,* in which we have to search the key.* @param iKey: Key needs to be search.* @return if key is found then returns index of key otherwaise -1*/int LinearSearch(struct Array objArr, int iKey){int iKeyIndex = -1;for(int i = 0; i < objArr.iLength; ++i){
if (objArr.A[i] == iKey){
iKeyIndex = i;break;}
}
return iKeyIndex;}int main(){Array objArr = {{2, 4, 6, 5, 7}, 5};int iIndex = LinearSearch(objArr, 7);if (iIndex != -1)cout << "Element found at index: " << iIndex << endl;elsecout << "Element not found." << endl;}You can also follow this link for more.
Comments
Post a Comment