#include<iostream>
#include<vector>
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;
}
void GetLeastNum(
int *nArray,
int nLength,
int k)
{
if(nArray == NULL || nLength <=
0)
throw exception(
"ERROR");
int nBegin =
0;
int nEnd = nLength-
1;
int nNum = Partion(nArray, nBegin, nEnd);
while(nNum != k+
1)
{
if(nNum > k+
1)
{
nNum = Partion(nArray, nBegin, nNum-
1);
}
else
{
nNum = Partion(nArray, nNum+
1, nEnd);
}
}
for(
int i =
0; i < k;++i)
{
cout<<nArray[i]<<
", ";
}
cout<<endl;
}
int main()
{
int a[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
0};
GetLeastNum(a,
10,
5);
}
转载请注明原文地址: https://ju.6miu.com/read-18541.html