/////////////////////////////////////////////////////////////////////////////////////////////
//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; }
原文地址:https://www.cnblogs.com/yzdai/p/11258624.html
时间: 2024-11-05 22:51:51