//最小堆实现 void MyGlobal::min_heapify(int *a, int* b,int left, int right) { int child = 0; int tmp = 0; int tempb = 0; int parent = left; assert(a != NULL); for (tmp = a[parent],tempb=b[parent]; LEFTSON(parent) <= right; parent = child) { child = LEFTSON(parent); if (child != parent && a[child] > a[child + 1]) { child++; } if (a[child] < tmp) { a[parent] = a[child]; b[parent] = b[child]; } else //满足最小堆的特性,直接退出 break; } a[parent] = tmp; b[parent] = tempb; } //创建最小堆 void MyGlobal::build_minheap(int *a,int*b, int size) { int i = PARENT(size); assert(a != NULL); for (; i >= 0; --i) { min_heapify(a,b, i, size - 1); } } //主函数 int* MyGlobal::find_Kmin_num_4(int *a, int* b, int size, int k) { int i = 0; assert(a != NULL); build_minheap(a, b, size - 1); int* m = new int[k]; for ( i = 0; i < k; ++i) { printf("%d\t", b[0]); //删除a[0],释放a[size-1-i] m[i] = b[0]; a[0] = a[size - 1 - i]; min_heapify(a,b ,0, size - 2 - i); } printf("\n"); return m; }
其中a是数组,b代表数组的下标。最后printf处如果输出a[0]就是数组最小的k项,输出b[0]就是数组最小k项的下标。b看需要可加可删
另外最大堆在:http://blog.chinaunix.net/uid-20937170-id-3347493.html
时间: 2024-11-09 10:54:00