Last active
December 17, 2015 17:18
-
-
Save ygabo/5644543 to your computer and use it in GitHub Desktop.
Extract the top K elements from a given set.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "topK.hpp" | |
using namespace std; | |
int main(){ | |
int xx[] ={124,34,324,54,6,645,33,43}; | |
vector<int> x(begin(xx), end(xx)); | |
int k = 5; | |
heapK<int> hpk(k); | |
for( auto it = x.begin(); it != x.end(); ++it ){ | |
cout<< *it << " "; | |
hpk.insert(*it); | |
} | |
cout << endl; | |
hpk.print(); | |
cin.get(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <vector> | |
#include <iostream> | |
#include <algorithm> //swap | |
using namespace std; | |
template<typename T> | |
class heapK{ | |
public: | |
heapK(); | |
heapK(size_t k); | |
void insert(T x); | |
void print(); | |
private: | |
vector<T> h; | |
void perc_down(size_t current); | |
void perc_up(size_t current); | |
size_t size; | |
size_t k; | |
}; | |
template<typename T> | |
heapK<T>::heapK():size(0){} | |
template<typename T> | |
heapK<T>::heapK(size_t k):h(k),size(0),k(k){} | |
template<typename T> | |
void heapK<T>::insert(T x){ | |
if(size < k){ | |
h[size] = x; | |
perc_up(size); | |
size++; | |
} | |
else{ | |
if(x > h[0]){ | |
h[0] = x; | |
perc_down(0); | |
size++; | |
} | |
} | |
} | |
template<typename T> | |
void heapK<T>::perc_down(size_t current){ | |
size_t last = k; | |
if( current >= last ) return; | |
size_t left = 2*current + 1; | |
size_t right = 2*current + 2; | |
size_t smaller = 0; | |
if( left < last && h[left] < h[current] ){ | |
smaller = left; | |
} | |
if( right < last && h[right] < h[left] ){ | |
smaller = right; | |
} | |
if( smaller ){ | |
swap(h[current], h[smaller]); | |
perc_down(smaller); | |
} | |
} | |
template<typename T> | |
void heapK<T>::perc_up(size_t current){ | |
if( current <= 0 ) return; | |
int parent = (current-1)/2; | |
if( h[current] < h[parent] ){ | |
swap(h[current], h[parent]); | |
perc_up(parent); | |
} | |
} | |
template<typename T> | |
void heapK<T>::print(){ | |
for( auto it = h.begin(); it != h.end(); ++it){ | |
cout << *it << " "; | |
} | |
cout << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use a min-heap to extract top K elements of data. Top here means max.