Compress the array into Ranges | Function to compress the array ranges ; start iteration from the ith array element ; loop until arr [ i + 1 ] == arr [ i ] and increment j ; if the program do not enter into the above while loop this means that ( i + 1 ) th element is not consecutive to i th element ; increment i for next iteration ; print the consecutive range found ; move i jump directly to j + 1 ; Driver code
def compressArr ( arr , n ) : NEW_LINE INDENT i = 0 ; NEW_LINE j = 0 ; NEW_LINE arr . sort ( ) ; NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i ; NEW_LINE while ( ( j + 1 < n ) and ( arr [ j + 1 ] == arr [ j ] + 1 ) ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] , " - " , arr [ j ] , end = " ▁ " ) ; NEW_LINE i = j + 1 ; NEW_LINE DEDENT DEDENT DEDENT n = 7 ; NEW_LINE arr = [ 1 , 3 , 4 , 5 , 6 , 9 , 10 ] ; NEW_LINE compressArr ( arr , n ) ; NEW_LINE