Find the smallest number in the rotation array in C++
- 2020-05-17 06:00:14
- OfStack
Interview question: rotate the smallest number in an array
Title: to move the first elements of an array to the end of the array, we call the rotation of the array. Input a rotation of an incrementing array and output the smallest element of the array. For example, the array {3,4,5,1,2} is one rotation of {1,2,3,4,5}, and the minimum value of the array is 1.
Algorithm:
(1) when the input rotation array is illegal: processing!
(2) when the input rotation array is normal, index1 = 0; index2 = length - 1:
a: if arry [index1]
<
When arry[index2] : indicates that the array is the original array and is not rotated;
b: if arry [index1]
>
When = arry[index2], middle = (index1+index2) /2:
b. 1 if arry [index1]
>
arry[middle],index2 = middle;
b. 2 if arry [index1]
<
= arry[middle],index1 = middle;
b.3 if arry[index1] = arry[middle] = arry[index2], traverse to find the minimum.
Code:
Min_RotateArray.hpp
#pragma once
#include<iostream>
using namespace std;
int Min_RotateArray(int arry[],int size)
{
if(arry == NULL || size <= 0)
{cout<<" Parameter input error!! "<<endl;}
int min = 0;
int index1 = 0;
int index2 = size-1;
int middle = (index1+index2)/2;
if(arry[0] < arry[size-1])
return arry[0];
while(arry[index1] >= arry[index2])
{
if(index2-index1 == 1)
{
min=index2;
break;
}
middle = (index1+index2)/2;
if(arry[index1] <= arry[middle])//arry[middle] Also in the first 1 In an increasing sequence
{
index1 = middle;
}
else
{
if(arry[index1] >= arry[middle])//arry[middle] In the first 2 In an increasing sequence
{index2 = middle;}
if(arry[index1] == arry[index2] && arry[index1] == arry[middle])
{
for(int i=0;i<size;++i)
{
if(arry[min]>arry[i])
{
min = i;
break;
}
}
}
}
}
return arry[min];
}
Min_RotateArray.cpp
#include"Min_RotateArray.hpp"
int main()
{
int arry[] = {3,4,5,1,2};
int size = sizeof(arry)/sizeof(arry[0]);
int min = Min_RotateArray(arry,size);
cout<<"The min is:"<<min<<endl;
system("pause");
return 0;
}
Thank you for reading, I hope to help you, thank you for your support of this site!