Check if an array is sorted and rotated | Function to check if an array is sorted and rotated clockwise ; Find the minimum element and it 's index ; Check if all elements before minIndex are in increasing order ; Check if all elements after minIndex are in increasing order ; Check if last element of the array is smaller than the element just starting element of the array for arrays like [ 3 , 4 , 6 , 1 , 2 , 5 ] - not sorted circular array ; Driver code ; Function Call
< ? php function checkIfSortRotated ( $ arr , $ n ) { $ minEle = PHP_INT_MAX ; $ maxEle = PHP_INT_MIN ; $ minIndex = -1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] < $ minEle ) { $ minEle = $ arr [ $ i ] ; $ minIndex = $ i ; } } $ flag1 = 1 ; for ( $ i = 1 ; $ i < $ minIndex ; $ i ++ ) { if ( $ arr [ $ i ] < $ arr [ $ i - 1 ] ) { $ flag1 = 0 ; break ; } } $ flag2 = 1 ; for ( $ i = $ minIndex + 1 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] < $ arr [ $ i - 1 ] ) { $ flag2 = 0 ; break ; } } if ( $ flag1 && $ flag2 && ( $ arr [ $ n - 1 ] < $ arr [ $ 0 ] ) ) echo ( " YES " ) ; else echo ( " NO " ) ; } $ arr = array ( 3 , 4 , 5 , 1 , 2 ) ; $ n = count ( $ arr ) ; checkIfSortRotated ( $ arr , $ n ) ; ? >