Sort elements of the array that occurs in between multiples of K | Utility function to print the contents of an array ; Function to sort elements in between multiples of k ; To store the index of previous multiple of k ; If it is not the first multiple of k ; Sort the elements in between the previous and the current multiple of k ; Update previous to be current ; Print the updated array ; Driver code
function printArr ( arr , n ) { for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } function sortArr ( arr , n , k ) { var prev = - 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { if ( prev != - 1 ) var tmp = arr . slice ( prev + 1 , i ) . sort ( ( a , b ) => a - b ) ; for ( var j = prev + 1 ; j < i ; j ++ ) { arr [ j ] = tmp [ j - prev - 1 ] ; } prev = i ; } } printArr ( arr , n ) ; } var arr = [ 2 , 1 , 13 , 3 , 7 , 8 , 21 , 13 , 12 ] ; var n = arr . length ; var k = 2 ; sortArr ( arr , n , k ) ;