简体   繁体   中英

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));

When you move the middle pointer, you need to round it up, eg (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 middle === last || middle === first before the value check to prevent invalid index errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM