Find the minimum element in a sorted and rotated array | Javascript program to find minimum element in a sorted and rotated array ; This condition is needed to handle the case when array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum element . Consider the cases like { 3 , 4 , 5 , 1 , 2 } ; Check if mid itself is minimum element ; Decide whether we need to go to left half or right half ; Driver Program
function findMin ( arr , low , high ) { if ( high < low ) return arr [ 0 ] ; if ( high == low ) return arr [ low ] ; let mid = low + Math . floor ( ( high - low ) / 2 ) ; if ( mid < high && arr [ mid + 1 ] < arr [ mid ] ) return arr [ mid + 1 ] ; if ( mid > low && arr [ mid ] < arr [ mid - 1 ] ) return arr [ mid ] ; if ( arr [ high ] > arr [ mid ] ) return findMin ( arr , low , mid - 1 ) ; return findMin ( arr , mid + 1 , high ) ; } let arr1 = [ 5 , 6 , 1 , 2 , 3 , 4 ] ; let n1 = arr1 . length ; document . write ( " " + findMin ( arr1 , 0 , n1 - 1 ) + " " ) ; let arr2 = [ 1 , 2 , 3 , 4 ] ; let n2 = arr2 . length ; document . write ( " " + findMin ( arr2 , 0 , n2 - 1 ) + " " ) ; let arr3 = [ 1 ] ; let n3 = arr3 . length ; document . write ( " " + findMin ( arr3 , 0 , n3 - 1 ) + " " ) ; let arr4 = [ 1 , 2 ] ; let n4 = arr4 . length ; document . write ( " " + findMin ( arr4 , 0 , n4 - 1 ) + " " ) ; let arr5 = [ 2 , 1 ] ; let n5 = arr5 . length ; document . write ( " " + findMin ( arr5 , 0 , n5 - 1 ) + " " ) ; let arr6 = [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ] ; let n6 = arr6 . length ; document . write ( " " + findMin ( arr6 , 0 , n6 - 1 ) + " " ) ; let arr7 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ; let n7 = arr7 . length ; document . write ( " " + findMin ( arr7 , 0 , n7 - 1 ) + " " ) ; let arr8 = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 1 ] ; let n8 = arr8 . length ; document . write ( " " + findMin ( arr8 , 0 , n8 - 1 ) + " " ) ; let arr9 = [ 3 , 4 , 5 , 1 , 2 ] ; let n9 = arr9 . length ; document . write ( " " + findMin ( arr9 , 0 , n9 - 1 ) + " " ) ;