Aaron Aaron - 1 month ago 5
Javascript Question

Find smallest element in a sorted rotated array

My function to find the lowest element in alphabetical order in a sorted rotated array seems to work when the element is in the middle of the array and when the element is at the beginning of the array. What I cannot figure out is how to get the code to work when the element is at the end of the array. The smallest element in "Anna". Here is my code

function sorted_array(arr){
var first = 0;
var middle = arr.length/2;
var last = arr.length-1;

while(true){
if(arr[middle-1] > arr[middle] && arr[middle+1] > arr[middle] || middle === first
|| middle == last){
return arr[middle];
}
if(arr[middle] > arr[last] ){
first = middle;
middle = Math.floor((middle + last)/2);
} else{
last = middle;
middle = Math.floor((first + middle)/2);
}
}
}


var arr = [ "Celeste",
"Elon", "Giggli", "Jay", "Mavis", "Phoebe", "Thunder", "Anna"];
console.log(sorted_array(arr));

Answer

When you move the middle pointer, you need to round it up, e.g. (middle + left + 1)/2 in the part where you search the later part of the array. Otherwise you will never reach the last item.

In your case you get middle = 6, last = 7, (6+7)/2 = 6,5 ==> 6.

Also in your stopping condition, you should check if middle === last || middle === first before the value check to prevent invalid index errors.

Comments