数据结构练习(04)查找最小的k个元素
http://zhedahht.blog.163.com/blog/static/2541117420072432136859/
#include <iostream> #include <vector> #include <set> using namespace std; void findknumbers(const vector<int>& data, multiset<int, greater<int>>& leastheap, int k) { leastheap.clear(); if (k == 0 || data.size() < k) return; vector<int>::const_iterator iter = data.begin(); for (; iter != data.end(); ++iter) { if (leastheap.size() < k) leastheap.insert(*iter); else { multiset<int, greater<int>>::iterator iterfirst = leastheap.begin(); if (*iter < *(leastheap.begin())) { leastheap.erase(iterfirst); leastheap.insert(*iter); } } } } int main() { vector<int> data; for (int i = 100; i >= 0; --i) data.push_back(i); multiset<int, greater<int>> leastheap; findknumbers(data, leastheap, 10); multiset<int, greater<int>>::const_iterator iter = leastheap.begin(); for (; iter != leastheap.end(); ++iter) cout << *iter << ' '; return 0; }
自己写的:
#include <cstdio> #include <cstdlib> #include <cstring> int data[110]; int maxheap[110]; int heapsize; void swap(int &a, int &b) { int t = a; a = b, b = t; } void maxheapfixup(int i) { int j = i >> 1; while (j >= 1 && i > 1) { if (maxheap[j] >= maxheap[i]) break; swap(maxheap[i], maxheap[j]); i = j; j = i >> 1; } } void maxheapfixdown(int i) { int left = i << 1; while (left <= heapsize) { int p = left; int right = left + 1; if (right <= heapsize && maxheap[left] < maxheap[right]) p = right; if (maxheap[i] >= maxheap[p]) break; swap(maxheap[i], maxheap[p]); i = p; left = i << 1; } } void heapinsert(int n, int num) { maxheap[n] = num; maxheapfixup(n); } void findknumber(int n, int k) { heapsize = k; for (int i = 1; i <= heapsize; ++i) heapinsert(i, data[i]); for (int i = heapsize + 1; i <= n; ++i) if (data[i] < maxheap[1]) maxheap[1] = data[i], maxheapfixdown(1); } int main() { for (int i = 1; i <= 100; ++i) data[i] = 101 - i; findknumber(100, 10); for (int i = 1; i <= heapsize; ++i) printf("%d ", maxheap[i]); return 0; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------