Reallocation of elements based on Locality of Reference | C ++ program to implement search for an item that is searched again and again . ; A function to perform sequential search . ; Linearly search the element ; If not found ; Shift elements before one position ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool search ( int arr [ ] , int n , int x ) { int res = -1 ; for ( int i = 0 ; i < n ; i ++ ) if ( x == arr [ i ] ) res = i ; if ( res == -1 ) return false ; int temp = arr [ res ] ; for ( int i = res ; i > 0 ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ 0 ] = temp ; return true ; } int main ( ) { int arr [ ] = { 12 , 25 , 36 , 85 , 98 , 75 , 89 , 15 , 63 , 66 , 64 , 74 , 27 , 83 , 97 } ; int q [ ] = { 63 , 63 , 86 , 63 , 78 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; for ( int i = 0 ; i < m ; i ++ ) search ( arr , n , q [ i ] ) ? cout << " Yes ▁ " : cout << " No ▁ " ; return 0 ; }