#include<iostream>
using namespace std;
void Swap(
int &a,
int &b)
{
int temp = a;
a = b;
b = temp;
}
int Partion(
int *nArray,
int nBegin,
int nEnd)
{
if(nArray == NULL|| nBegin <
0 || nEnd<
0)
throw exception(
"ERROR");
int nPivot = nArray[nBegin];
int nLeft = nBegin;
int nRight = nEnd;
while(nLeft != nRight)
{
while(nArray[nRight]>=nPivot && nLeft < nRight)
--nRight;
while(nArray[nLeft]<=nPivot && nLeft < nRight)
++nLeft;
if(nLeft<nRight)
{
Swap(nArray[nLeft], nArray[nRight]);
}
}
Swap(nArray[nBegin], nArray[nLeft]);
return nLeft;
}
int FindMoreThanHalfNum(
int *nArray,
int nLength)
{
if(nArray == NULL || nLength <=
0)
throw exception(
"ERROR");
int nMiddle = nLength>>
1;
int nBegin =
0;
int nEnd = nLength-
1;
int nNum = Partion(nArray, nBegin, nEnd);
while(nNum != nMiddle)
{
if(nNum > nMiddle)
{
nNum = Partion(nArray, nBegin, nNum-
1);
}
else
{
nNum = Partion(nArray, nNum+
1, nEnd);
}
}
return nArray[nNum];
}
int main()
{
int a[] = {
0,
1,
2,
2,
2,
2,
2,
2,
2,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
4,
5,
6};
cout<<FindMoreThanHalfNum(a,
25);
}
#include<iostream>
using namespace std;
int FindMoreThanHalfNum(
int * nArray,
int nLength)
{
if(nArray == NULL || nLength <=
0)
throw exception(
"ERROR");
int nNum = nArray[
0];
int nCount =
1;
for(
int i =
1; i < nLength; ++i)
{
if(nArray[i] == nNum)
++nCount;
else
{
--nCount;
if(!nCount)
{
nNum = nArray[i];
++nCount;
}
}
}
return nNum;
}
int main()
{
int a[] = {
0,
1,
2,
2,
2,
2,
2,
2,
2,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
4,
5,
6};
cout<<FindMoreThanHalfNum(a,
25)<<endl;
}
转载请注明原文地址: https://ju.6miu.com/read-20397.html