Compress the array into Ranges | Java program to compress the array 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
import java . util . Arrays ; class GFG { static void compressArr ( int arr [ ] , int n ) { int i = 0 , j = 0 ; Arrays . sort ( arr ) ; while ( i < n ) { j = i ; while ( ( j + 1 < n ) && ( arr [ j + 1 ] == arr [ j ] + 1 ) ) { j ++ ; } if ( i == j ) { System . out . print ( arr [ i ] + " ▁ " ) ; i ++ ; } else { System . out . print ( arr [ i ] + " - " + arr [ j ] + " ▁ " ) ; i = j + 1 ; } } } public static void main ( String [ ] args ) { int n = 7 ; int arr [ ] = { 1 , 3 , 4 , 5 , 6 , 9 , 10 } ; compressArr ( arr , n ) ; } }