Check if array elements are consecutive | Added Method 3 |  ; Helper functions to get minimum and maximum in an array ; The function checks if the array elements are consecutive If elements are consecutive , then returns true , else returns false ; 1 ) Get the minimum element in array ; 2 ) Get the maximum element in array ; 3 ) max - min + 1 is equal to n then only check all elements ; if the value at index j is negative then there is repetition ; If we do not see a negative value then all elements are distinct ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int getMin ( int arr [ ] , int n ) ; int getMax ( int arr [ ] , int n ) ; bool areConsecutive ( int arr [ ] , int n ) { if ( n < 1 ) return false ; int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; if ( max - min + 1 == n ) { int i ; for ( i = 0 ; i < n ; i ++ ) { int j ; if ( arr [ i ] < 0 ) j = - arr [ i ] - min ; else j = arr [ i ] - min ; if ( arr [ j ] > 0 ) arr [ j ] = - arr [ j ] ; else return false ; } return true ; } return false ; } int getMin ( int arr [ ] , int n ) { int min = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] < min ) min = arr [ i ] ; return min ; } int getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max ) max = arr [ i ] ; return max ; } int main ( ) { int arr [ ] = { 1 , 4 , 5 , 3 , 2 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( areConsecutive ( arr , n ) == true ) printf ( " ▁ Array ▁ elements ▁ are ▁ consecutive ▁ " ) ; else printf ( " ▁ Array ▁ elements ▁ are ▁ not ▁ consecutive ▁ " ) ; getchar ( ) ; return 0 ; }