Check if an element is present in an array using at most floor ( N / 2 ) + 2 comparisons | Function to check whether X is present in the array A [ ] ; Initialise a pointer ; Store the number of comparisons ; Variable to store product ; Check is N is odd ; Update i and T ; Traverse the array ; Check if i < N ; Update T ; Check if T is equal to 0 ; Given Input ; Function Call
function findElement ( A , N , X ) { var i = 0 ; var Comparisons = 0 ; var T = 1 ; var Found = " " ; Comparisons += 1 ; if ( N % 2 == 1 ) { i = 1 ; T *= ( A [ 0 ] - X ) ; } for ( ; i < N ; i += 2 ) { Comparisons += 1 ; T *= ( A [ i ] - X ) ; T *= ( A [ i + 1 ] - X ) ; } Comparisons += 1 ; if ( T == 0 ) { document . write ( " " + Comparisons ) ; } else { document . write ( " " ) ; } } var A = [ - 3 , 5 , 11 , 3 , 100 , 2 , 88 , 22 , 7 , 900 , 23 , 4 , 1 ] ; var N = A . length ; var X = 1 ; findElement ( A , N , X ) ;