Move to Front/Head Method of Linear search:
# Move to Front/Head Method of Linear search:
In this method of searching, If the key is found then it is swapped with the first element of the array.
The idea behind this method is if the item will be searched again, then the item will search very fast.
Below is the program for this method.
#include <iostream>
using namespace std;
/**
* @brief The Array struct: Structure Which Contains array of size 10 and arrays* Length (number of items it contains.)*/struct Array{int A[10];int iLength;};
/**
* @brief swap: This function swaps the items.
* @param pFirst: First item.
* @param pSecond: Second item
*/
void swap(int *pFirst, int *pSecond)
{
int iTemp;
iTemp = *pFirst;
*pFirst = *pSecond;
*pSecond = iTemp;
}
/**
* @brief moveToHeadLinearSearch: This methods search the Key in the array passed in first param,* and if item/key is found then, swap it with the item at 0th index.* @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 moveToHeadLinearSearch(struct Array objArr, int iKey){int iKeyIndex = -1;for(int i = 0; i < objArr.iLength; ++i){
if (objArr.A[i] == iKey){
swap(objArr.A[i], objArr.A[0]);iKeyIndex = 0;break;}
}
return iKeyIndex;}int main(){Array objArr = {{2, 4, 6, 5, 7}, 5};int iIndex = moveToHeadLinearSearch(objArr, 7);if (iIndex != -1)cout << "Element found at index: " << iIndex << endl;elsecout << "Element not found." << endl;}
Comments
Post a Comment