Minimum peak elements from an array by their repeated removal at every iteration of the array | Function to return the list of minimum peak elements ; Length of original list ; Initialize resultant list ; Traverse each element of list ; Length of original list after removing the peak element ; Traverse new list after removal of previous min peak element ; Update min and index , if first element of list > next element ; Update min and index , if last element of list > previous one ; Update min and index , if list has single element ; Update min and index , if current element > adjacent elements ; Remove current min peak element from list ; Insert min peak into resultant list ; Print resultant list ; Given array arr [ ] ; Function call
function minPeaks ( list ) { var n = list . length ; var result = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { var min = 1000000000 ; var index = - 1 ; var size = list . length ; for ( var j = 0 ; j < size ; j ++ ) { if ( j == 0 && j + 1 < size ) { if ( list [ j ] > list [ j + 1 ] && min > list [ j ] ) { min = list [ j ] ; index = j ; } } else if ( j == size - 1 && j - 1 >= 0 ) { if ( list [ j ] > list [ j - 1 ] && min > list [ j ] ) { min = list [ j ] ; index = j ; } } else if ( size == 1 ) { min = list [ j ] ; index = j ; } else if ( list [ j ] > list [ j - 1 ] && list [ j ] > list [ j + 1 ] && min > list [ j ] ) { min = list [ j ] ; index = j ; } } list . splice ( index , 1 ) ; result . push ( min ) ; } document . write ( " " ) ; for ( var i = 0 ; i < result . length ; i ++ ) { document . write ( result [ i ] + " " ) ; } document . write ( " " ) ; } var arr = [ 1 , 9 , 7 , 8 , 2 , 6 ] ; minPeaks ( arr ) ;