Code to find minimum element in a sorted rotated array (javascript)


#1

Consider a sorted array

1 2 3 4 5 6 7 8

lets say it is rotated by position 3

so array becomes

4 5 6 7 8 1 2 3

we have to find minimum element in such rotated sorted array

var c = [10,12,14,18,1,2,3];

//1 2 3 20 30 40 19

//10 20 18 15 4 3 2

function minRotated(a)
{

var low = 0;
var high = a.length -1;


while(low<=high)
{



	if(low == high)
	{

		console.log(a[low]);

		return a[low];
	}

		var mid = low + Math.floor((high - low)/2) ;

		console.log("low " + low + "high " + high + "mid " + mid);




if(a[mid] - a[mid -1] < 0 && a[mid] - a[mid + 1] < 0)
{
		//console.log(a[mid]);
		return a[mid];
}


if(a[high] > a[mid])
	high = mid -1;

else
	low = mid + 1;

}

}

console.log(minRotatedĀ©);