Search an element in an unsorted array using minimum number of comparisons | C ++ implementation to search an element in the unsorted array using minimum number of comparisons ; function to search an element in minimum number of comparisons ; 1 st comparison ; no termination condition and thus no comparison ; this would be executed at - most n times and therefore at - most n comparisons ; replace arr [ n - 1 ] with its actual element as in original ' arr [ ] ' ; if ' x ' is found before the ' ( n - 1 ) th ' index , then it is present in the array final comparison ; else not present in the array ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string search ( int arr [ ] , int n , int x ) { if ( arr [ n - 1 ] == x ) return " Found " ; int backup = arr [ n - 1 ] ; arr [ n - 1 ] = x ; for ( int i = 0 ; ; i ++ ) { if ( arr [ i ] == x ) { arr [ n - 1 ] = backup ; if ( i < n - 1 ) return " Found " ; return " Not ▁ Found " ; } } } int main ( ) { int arr [ ] = { 4 , 6 , 1 , 5 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 1 ; cout << search ( arr , n , x ) ; return 0 ; }