Check if an array is Wave Array | Function to check if array is wave array arr : input array n : size of array ; Check the wave form * If arr [ 1 ] is greater than left and right * Same pattern will be followed by whole * elements , else reverse pattern * will be followed by array elements ; Check for last element ; Check for last element ; Array
< ? php function isWaveArray ( $ arr , $ n ) { $ result = true ; if ( $ arr [ 1 ] > $ arr [ 0 ] && $ arr [ 1 ] > $ arr [ 2 ] ) { for ( $ i = 1 ; $ i < ( $ n - 1 ) ; $ i += 2 ) { if ( $ arr [ $ i ] > $ arr [ $ i - 1 ] && $ arr [ $ i ] > $ arr [ $ i + 1 ] ) { $ result = true ; } else { $ result = false ; break ; } } if ( $ result == true && $ n % 2 == 0 ) { if ( $ arr [ $ n - 1 ] <= $ arr [ $ n - 2 ] ) { $ result = false ; } } } else if ( $ arr [ 1 ] < $ arr [ 0 ] && $ arr [ 1 ] < $ arr [ 2 ] ) { for ( $ i = 1 ; $ i < $ n - 1 ; $ i += 2 ) { if ( $ arr [ $ i ] < $ arr [ $ i - 1 ] && $ arr [ $ i ] < $ arr [ $ i + 1 ] ) { $ result = true ; } else { $ result = false ; break ; } } if ( $ result == true && $ n % 2 == 0 ) { if ( $ arr [ $ n - 1 ] >= $ arr [ $ n - 2 ] ) { $ result = false ; } } } return $ result ; } $ arr = array ( 1 , 3 , 2 , 4 ) ; $ n = sizeof ( $ arr ) ; if ( isWaveArray ( $ arr , $ n ) ) { echo " YES " ; } else { echo " NO " ; } ? >