解法五
复杂度O(n),应用场合为,所有的N个数都是正整数,取值范围不大。
代码如下:
下面使用最大堆求k min,
/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
#define INF 65535
int array[] = {1111, 22222, 3000, 4, 34, 313, 13, 132409, 340, 43, 588, 30, 2,
237, 999, 90, 3, 5, 1, 7, 8};
const int size = sizeof array / sizeof *array;
const int heapSize = 4;
int maxHeap[heapSize];
void keepHeap(int (&heap)[heapSize], int pos)
{
if(pos >= heapSize)
return;
int maxPos = pos;
if(2 * pos + 1 < heapSize && heap[pos] < heap[2 * pos + 1])
maxPos = 2 * pos + 1;
if(2 * pos + 2 < heapSize && heap[maxPos] < heap[2 * pos + 2])
maxPos = 2 * pos + 2;
if(maxPos != pos) {
swap(heap[pos], heap[maxPos]);
keepHeap(heap, maxPos);
}
}
void keepHeap2(int (&heap)[heapSize], int pos)
{
if(pos >= heapSize)
return;
while(pos < heapSize) {
int maxPos = pos * 2 + 1;
if(maxPos >= heapSize)
break;
if(maxPos + 1 < heapSize && heap[maxPos] < heap[maxPos + 1])
maxPos++;
if(heap[pos] < heap[maxPos]) {
swap(heap[pos], heap[maxPos]);
pos = maxPos;
} else
break;
}
}
void process(int (&array)[size])
{
for(int i = 0; i < heapSize; i++) {
maxHeap[i] = INF;
}
for(int i = 0; i < size; i++) {
if(*maxHeap > array[i]) {
*maxHeap = array[i];
keepHeap2(maxHeap, 0);
copy(maxHeap, maxHeap + heapSize, ostream_iterator<int>(cout, " "));
cout << endl;
}
}
}
void main()
{
cout << "----------------------------------------------------------------------" << endl;
process(array);
cout << "----------------------------------------------------------------------" << endl;
cout << "result:" << endl;
copy(maxHeap, maxHeap + heapSize, ostream_iterator<int>(cout, " "));
}