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 Program
function countRotation ( arr , low , high ) { if ( low > high ) { return 0 ; } let mid = low + Math . floor ( ( high - low ) / 2 ) ; if ( mid < high && arr [ mid ] > arr [ mid + 1 ] ) { return mid + 1 ; } if ( mid > low && arr [ mid ] < arr [ mid - 1 ] ) { return mid ; } if ( arr [ mid ] > arr [ low ] ) { return countRotation ( arr , mid + 1 , high ) ; } if ( arr [ mid ] < arr [ high ] ) { return countRotation ( arr , low , mid - 1 ) ; } else { let rightIndex = countRotation ( arr , mid + 1 , high ) ; let leftIndex = countRotation ( arr , low , mid - 1 ) ; if ( rightIndex == 0 ) { return leftIndex ; } return rightIndex ; } } let arr1 = [ 4 , 5 , 1 , 2 , 3 ] ; document . write ( countRotation ( arr1 , 0 , arr1 . length - 1 ) ) ;