Learning note 11 - minimum number of rotation array

Keywords: less

Title: move the first several elements of an array to the end of the array, which we call array rotation.
Input a rotation of an increasing sort array, and output the minimum elements of the rotation array. For example, array {3, 4, 5, 1, 2} is a rotation of {1, 2, 3, 4, 5} and the minimum value of the array is 1.
Idea: using binary search method, use two pointers index1 and index2 to point to the first and last element of the array respectively, and then find the element indexMid in the middle of the array. If the value of index1 is less than the intermediate element, point the first pointer to the intermediate element, and the first pointer after moving is still in the increasing sub array in front; if the value of index2 is greater than the intermediate element , will point the second pointer to the intermediate element, and the second pointer after the move will still be in the following incrementing sub array. When the distance between two pointers is 1, the element pointed by the second pointer is the minimum number.
The core code is as follows:

int MinInOrder(int* numbers, int index1, int index2); // Declaration order lookup

int Min(int* numbers, int length)
    if(numbers == nullptr || length <= 0)
        throw new std::exception("Invalid parameters");
    int index1 = 0;
    int index2 = length - 1;
    int indexMid = index1;  // If the rotated array is still sorted, the first number can be returned directly
    while(numbers[index1] >= numbers[index2])
        // If index1 and index2 point to two adjacent numbers,
        // index1 points to the last number of the first increasing sub array,
        // index2 points to the first number of the second subarray, which is the smallest number in the array
        if(index2 - index1 == 1)
            indexMid = index2;
        // If the subscripts index1, index2 and indexMid point to the same three numbers,
        // You can only search in order
        indexMid = (index1 + index2) / 2;
        if(numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1])
            return MinInOrder(numbers, index1, index2);

        // Narrow the search
        if(numbers[indexMid] >= numbers[index1])
            index1 = indexMid;
        else if(numbers[indexMid] <= numbers[index2])
            index2 = indexMid;
    return numbers[indexMid];

int MinInOrder(int* numbers, int index1, int index2)  // Sequential search
    int result = numbers[index1];
    for(int i = index1 + 1; i <= index2; ++i)
        if(result > numbers[i])
            result = numbers[i];
    return result;

Posted by jlive on Wed, 04 Dec 2019 13:04:10 -0800