Search an element in an 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
function search ( arr , n , x ) { if ( arr [ n - 1 ] == x ) return " " ; let backup = arr [ n - 1 ] ; arr [ n - 1 ] = x ; for ( let i = 0 ; ; i ++ ) { if ( arr [ i ] == x ) { arr [ n - 1 ] = backup ; if ( i < n - 1 ) return " " ; return " " ; } } } let arr = [ 4 , 6 , 1 , 5 , 8 ] ; let n = arr . length ; let x = 1 ; document . write ( search ( arr , n , x ) ) ;