text: Check if an array is Wave Array | Java code to check if the 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 ; Driver code ; Array
code: public class GFG { static boolean isWaveArray ( int arr [ ] , int n ) { boolean result = true ; if ( arr [ 1 ] > arr [ 0 ] && arr [ 1 ] > arr [ 2 ] ) { for ( int 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 ( int 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 ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int n = arr . length ; if ( isWaveArray ( arr , n ) ) { System . out . println ( " YES " ) ; } else { System . out . println ( " NO " ) ; } } }