手写topN算法-c语言
#include <stdio.h> #include <malloc.h> struct TreeHeap { int v; }; typedef struct TreeHeap TreeHeap; static void print_bp(int bp[],int len); void create_treeheap(TreeHeap *treeheap, int data[10],int bp[11]) { treeheap->v = 1; // from bottom to top adjust heap int i=0; for (i=0;i<10;i++) { bp[i+1] = data[i]; if (i!=0) { int j = i+1; while(j>1) { if (bp[j] > bp[j/2]) // todo 需要加上和邻居的对比,max(m,m+1)和m/2对比,大的在上面? { int tmp = bp[j/2]; bp[j/2] = bp[j]; bp[j] = tmp; } j = j/2; } } } } void add_v(int bp[],int len,int v) { int i=1; for (i=1;i<len;i++) { if (bp[i] == 0) { bp[i] = v; break; } } while (i>1) { if (bp[i] > bp[i/2]) // swap { int tmp = bp[i]; bp[i] = bp[i/2]; bp[i/2] = tmp; } i = i/2; } } void pull_top1(int bp[],int len) { int i=1; printf("pop v %d\n",bp[1]); for (i=1;i<len;i++) { if (bp[i]==0) { bp[1] = bp[i-1]; bp[i-1]=0; break; } } int size = len-1; i = 1; // adjust heap while (bp[i] != 0 && i<=size/2) { int max_child = bp[i*2] > bp[i*2+1] ? i*2 : i*2+1; if (bp[i] < bp[max_child]) { int tmp = bp[i]; bp[i] = bp[max_child]; bp[max_child] = tmp; i=max_child; } else { printf("adjust done\n"); break; } print_bp(bp,size); printf("\n"); } } void pull_topN(int bp[],int len,int n) { int i=1; for (i = 1;i<=n;i++) { pull_top1(bp,len); } } void print_bp(int bp[],int len) { int i=1; for (i=1;i<len;i++) { if (bp[i] == 0) return; printf("%d ",bp[i]); } } void print_bp(int bp[],int len, bool add_newline) { print_bp(bp,len); if (add_newline) { printf("\n"); } } int main(){ // tree storage TreeHeap *treeheap = (TreeHeap *) malloc(sizeof(TreeHeap)); int data[10] = {1,2,3,11,10,56,4,5,7,9}; int bp[31] = {}; create_treeheap(treeheap, data,bp); printf("初始堆\n"); print_bp(bp,31); printf("\n"); add_v(bp,31,10); printf("add 10\n"); print_bp(bp,31); printf("\n"); printf("pop 1\n"); pull_top1(bp,31); print_bp(bp,31); printf("\n"); printf("pop 1\n"); pull_top1(bp,31); print_bp(bp,31); printf("\n"); printf("add 10\n"); add_v(bp,31,10); print_bp(bp,31); printf("\n"); printf("top 3\n"); pull_topN(bp,31,3); print_bp(bp,31); printf("\n"); printf("add 1\n"); add_v(bp,31,1); print_bp(bp,31); printf("\n"); printf("top 3\n"); pull_topN(bp,31,3); print_bp(bp,31); printf("\n"); return 0; }