Example #1
0
int main()
{
	MinHeap<int> minHeap;
	MaxHeap<int> maxHeap;

	minHeap.push(10);
	minHeap.push(5);
	minHeap.push(12);
	minHeap.push(3);
	minHeap.push(4);

	maxHeap.push(10);
	maxHeap.push(5);
	maxHeap.push(12);
	maxHeap.push(3);
	maxHeap.push(4);

	while ( !minHeap.empty()) {
		std::cout << minHeap.top() << " ";
		minHeap.pop();
	}
	std::cout << std::endl;

	while ( !maxHeap.empty()) {
		std::cout << maxHeap.top() << " ";
		maxHeap.pop();
	}
	std::cout << std::endl;
}
Example #2
0
void printLocalMax(const int *arr, size_t len, size_t window) {
  MaxHeap<ValueWrapper> h;
  for (int i = 0; i < window - 1; ++i) {
    h.add(ValueWrapper(arr[i], i));
  }
  for (int i = window - 1; i < len; ++i) {
    h.add(ValueWrapper(arr[i], i));
    for(;;) {
      ValueWrapper *r = h.top();
      if (i - r->pos < window) {
	cout << r->value << endl;
	break;
      }
      h.pop();
    }
  }
}
  void addNum(int num) {
    if (max_heap_.empty()) {
      max_heap_.push(num);
    } else {
      if (num > max_heap_.top()) {
        min_heap_.push(num);
      } else {
        max_heap_.push(num);
      }

      // Maintain abs(max_heap_.size() - min_heap_.size()) <= 1
      if (max_heap_.size() > min_heap_.size() + 1) {  // max_heap_ too large
        min_heap_.push(max_heap_.top());
        max_heap_.pop();
      } else if (min_heap_.size() >
                 max_heap_.size() + 1) {  // min_heap_ too large
        max_heap_.push(min_heap_.top());
        min_heap_.pop();
      }
    }
  }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
	if( nrhs!=1 )
		mexErrMsgTxt("This function requires 3 arguments\n");
	if( !mxIsNumeric(prhs[0]) )
		mexErrMsgTxt("parameter 1 missing!\n");

	// retrieve the heap
	MaxHeap<double>*  heap;
	retrieve_heap( prhs[0], heap);


	// extract head before popping
	pair<double, int> curr = heap->top();
	plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
	*mxGetPr(plhs[0]) = curr.second+1;
	plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
	*mxGetPr(plhs[1]) = curr.first;

	// pop top element in the PQ
	heap->pop();
}
Example #5
0
namespace max_heap_test {

  TEST_CASE( "Basic FIFO operations maintains max ordering", "[min_heap]" ) {
    MaxHeap<int> h;

    REQUIRE( h.size() == 0 );

    h.insert(5);
    REQUIRE( h.peek() == 5 );

    h.insert(4);
    REQUIRE( h.peek() == 5 );

    h.insert(6);
    REQUIRE( h.peek() == 6 );

    REQUIRE( h.pop() == 6 );
    REQUIRE( h.pop() == 5 );
    REQUIRE( h.pop() == 4 );

    for(int i=0; i<500; i++){
      h.insert(rand() % 100);
    }
    for(int i=0; i<h.size(); i++){
      REQUIRE( h.pop() >= h.peek() );
    }
  }

}