一、topk_堆排
#include
#include
#include
//堆排序
using namespace std;
void Swap(vector& tree, int a, int b) {
int temp = tree[a];
tree[a] = tree[b];
tree[b] = temp;
}
void heapify(vector& tree, int n, int i) {
if (i >= n)
return;
int min = i;
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
if (c1& tree,int n) {
for (int i = 0; i < n; i++) {
printf("%d ", tree[i]);
}
printf("\n");
}
void build_heap(vector& tree,int n) {
int last_node = n - 1;
int parent = (last_node - 1) / 2;
for (int i = parent; i >= 0; i--) {
heapify(tree, n, i);
}
}
//核心
void heap_sort(vector&arr,vector&tree,int n) {
for (int i = n+1; i < arr.size();i++) {
build_heap(tree, n);
print(tree, n);
if (arr[i] > tree[0]) {
tree[0] = arr[i];
}
}
}
int main() {
vector tree = { 2,3,4,15,2,15,534,34,53,4645,6,1234,23423,23423,2,6354,62,54123,4,12 };
/*验证
sort(tree.begin(), tree.end());
print(tree, tree.size());*/
vector arr = tree;
int n = 7;
heap_sort(arr,tree, n);
return 0;
}
二、topk_sort排序
#include
#include
#include
template
void sorts(std::vector& v) {
// sort vector ----- Ascend
sort(v.begin(), v.end());
}
template
void print(std::vector& v) {
for (auto num : v)
std::cout << num << " ";
std::cout << std::endl;
}
template
std::vector topK(std::vector& v, int k) {
std::vector tmp(v.begin(), v.begin() + k);
for (int i = k + 1; i < v.size(); ++i) {
sorts(tmp);
print(tmp);
if (v[i] < tmp[0])
continue;
tmp[0] = v[i];
}
return tmp;
}
int main() {
std::vector v = { 2,3,4,15,2,15,534,34,53,4645,6,1234,23423,23423,2,6354,62,54123,4,12 };
std::vector res = topK(v, 7);
print(res);
return 0;
}