- 基于Partition的方法:
int Partition(int* pData, int begin, int end)
{
int pivot = pData[begin];
int left = begin;
int right = end;
while (left < right)
{
while (left < right && pData[right] >= pivot) --right;
while (left < right && pData[left] <= pivot) ++left;
if (left < right) std::swap(pData[left], pData[right]);
}
if (begin != left) std::swap(pData[begin], pData[left]);
return left;
}
void GetLeastLessKData(int* pData, int size, int count, int* pDestData)
{
int begin = 0;
int end = size - 1;
int destIdx = count - 1;
int curIdx = Partition(pData, begin, end);
while (curIdx != destIdx)
{
if (curIdx < destIdx) curIdx = Partition(pData, curIdx + 1, end);
else curIdx = Partition(pData, begin, curIdx - 1);
}
for (int idx = 0; idx < count; ++idx) pDestData[idx] = pData[idx];
}
void GetLeastLessKData(int* pData, int size, int count)
{
if (nullptr == pData || size < 1 || count < 1 || count > size) return;
int* pDestData = new int[count];
GetLeastLessKData(pData, size, count, pDestData);
for (int idx = 0; idx < count; ++idx) std::cout << pData[idx] << " ";
std::cout << std::endl;
delete pDestData;
}
- 基于最大堆的方法:
void GetLeastLessKData(int* pData, int size, int count)
{
if (nullptr == pData || size < 1 || count < 1 || count > size) return;
int* pDestData = new int[count];
for (int idx = 0; idx < count; ++idx) pDestData[idx] = pData[idx];
for (int idx = count; idx < size; ++idx)
{
std::make_heap(pDestData, pDestData + count);
if (pData[idx] < pDestData[0]) pDestData[0] = pData[idx];
}
for (int idx = 0; idx < count; ++idx) std::cout << pDestData[idx] << " ";
std::cout << std::endl;
delete pDestData;
}