-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtop_k.cpp
More file actions
72 lines (70 loc) · 1.72 KB
/
top_k.cpp
File metadata and controls
72 lines (70 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <assert.h>
/*max heap
>>left child>>>> >>left child>>>>
↑ ↓ ↑ ↓
--↑--------------↓--↑--------------↓----------------------
| root 6 | 5 | 4 | 3 | 2 | 1 |
--↓--------------↓-------↑--↓----------------↑-----↑------
↓ >>>>>>>>↑>>↓>>right child>>>> ↑
>>>>>>>right child>>>>>> >>>>>left child>>>>>>>>
*/
void adjust_max_heap(int *heap,int index,int end);
void build_max_heap(int *heap,int size);
void top_k(int *arr,int size,int *out,int k);
int main(int argc, char const *argv[])
{
int arr[]={32, 54, 43, 56, 6, 4, 35, 17, 87, 31};
int k=6;
int *out=new int[k];
top_k(arr,10,out,k);
for (int i = 0; i < k; ++i)
{
std::cout<<out[i]<<' ';
}
std::cout<<std::endl;
delete out;
return 0;
}
void adjust_max_heap(int *heap,int index,int end)
{
assert(heap!=NULL);
int tmp = heap[index];
for (int child; index <end; index=child)
{
child=2*index+1;
if(child>=end) break;
if(heap[child]<heap[child+1])
++child;
if(tmp<heap[child])
heap[index]=heap[child];
else
break;
}
heap[index]=tmp;
}
void build_max_heap(int *heap,int size)
{
assert(heap!=NULL);
for (int i = 0; i < size; ++i)
{
adjust_max_heap(heap,i,size-1);
}
}
void top_k(int *arr,int size,int *out,int k)
{
assert(arr!=NULL&&out!=NULL);
for (int i = 0; i < k; ++i)
{
out[i]=arr[i];
}
build_max_heap(out,k);
for (int i = k; i < size; ++i)
{
if(arr[i]<out[0])
{
out[0]=arr[i];
adjust_max_heap(out,0,k-1);
}
}
}