Count of rotations required to generate a sorted array | Function to return the count of rotations ; If array is not rotated ; Check if current element is greater than the next element ; The next element is the smallest ; Check if current element is smaller than it 's previous  element ; Current element is the smallest ; Check if current element is greater than lower bound ; The sequence is increasing so far Search for smallest element on the right subarray ; Smallest element lies on the left subarray ; Search for the smallest element on both subarrays ; Driver code
def countRotation ( arr , low , high ) : NEW_LINE INDENT if ( low > high ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mid = low + ( high - low ) // 2 NEW_LINE if ( mid < high and arr [ mid ] > arr [ mid + 1 ] ) : NEW_LINE INDENT return mid + 1 NEW_LINE DEDENT if ( mid > low and arr [ mid ] < arr [ mid - 1 ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( arr [ mid ] > arr [ low ] ) : NEW_LINE INDENT return countRotation ( arr , mid + 1 , high ) NEW_LINE DEDENT if ( arr [ mid ] < arr [ high ] ) : NEW_LINE INDENT return countRotation ( arr , low , mid - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT rightIndex = countRotation ( arr , mid + 1 , high ) NEW_LINE leftIndex = countRotation ( arr , low , mid - 1 ) NEW_LINE if ( rightIndex == 0 ) : NEW_LINE INDENT return leftIndex NEW_LINE DEDENT return rightIndex NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 4 , 5 , 1 , 2 , 3 ] NEW_LINE N = len ( arr1 ) NEW_LINE print ( countRotation ( arr1 , 0 , N - 1 ) ) NEW_LINE DEDENT