码迷,mamicode.com
首页 > 编程语言 > 详细

题目八:旋转数组的最小数字

时间:2019-07-28 13:52:58      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:led   div   UNC   min   pad   star   search   index   iar   

/////////////////////////////////////////////////////////////////////////////////////////////
//12. 题目八:旋转数组的最小数字

int RotatedBinarySearchMinNum(int aiArray[], int iLen)
{
    int iLeft = 0;
    int iMid = 0;
    int iRight = iLen - 1;

    while (aiArray[iLeft] >= aiArray[iRight])
    {
        if (iRight - iLeft == 1)
        {
            iMid = iRight;
            break;
        }

        iMid = iLeft + (iRight - iLeft) / 2;
        if (aiArray[iMid] >= aiArray[iLeft])
        {
            iLeft = iMid; 
        }
        else if (aiArray[iMid] <= aiArray[iRight])
        {
            iRight = iMid;
        }
    }

    return aiArray[iMid];
}

// 旋转数组中查找
int RotatedBinarySearch(int aiArray[], int iLen, int iTarget)
{
    int iLeft = 0;
    int iMid = 0;
    int iRight = iLen - 1;

    while (iLeft <= iRight)
    {
        iMid = iLeft + (iRight - iLeft) / 2;
        if (aiArray[iMid] == iTarget)
        {
            return iMid;
        }
        
        // 情况一:旋转点在中位数的右侧
        if (aiArray[iMid] >= aiArray[iLeft])
        {
            // 最左侧元素 <= 查找目标 < 中位数
            if (aiArray[iLeft] <= iTarget && iTarget < aiArray[iMid])
            {
                iRight = iMid - 1;
            }
            else
            {
                iLeft = iMid + 1;
            }
        }
        // 情况二: 旋转点在中位数的左侧
        else
        {
            // 中位数 < 查找目标 <= 最右侧元素
            if (aiArray[iMid] < iTarget && iTarget <= aiArray[iRight])
            {
                iLeft = iMid + 1;
            }
            else
            {
                iRight = iMid - 1;
            }
        }
    }

    return -1;
}

void RotatedBinarySearchTestFunc()
{
    cout << "\n\n --------------- RotatedBinarySearchTestFunc Start -------------->" << endl;
    int aiArray[] = {9, 10, 11, 12, 13, 1, 3, 4, 5, 8};
    int iLen = sizeof(aiArray) / sizeof(int);
    TRAVERSAL_ARRAY(aiArray, iLen);
    
    cout << "旋转数组中最小数字: " << RotatedBinarySearchMinNum(aiArray, iLen) << endl;

    int iFindNum = 5;
    int iIndex = RotatedBinarySearch(aiArray, iLen, iFindNum);
    if (iIndex > 0)
    {
        printf("Find %02d[%02d] Success!", iFindNum, iIndex);
    }
    else 
    {
        cout << "Find: " << iFindNum << " Failed!" << endl;
    }

    cout << "\n\n --------------- RotatedBinarySearchTestFunc Start -------------->" << endl;

}

题目八:旋转数组的最小数字

标签:led   div   UNC   min   pad   star   search   index   iar   

原文地址:https://www.cnblogs.com/yzdai/p/11258624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!